Recently I found out that I can't use computed property or a data properties within the components slot. Even though computed is defined in the component, I am not able to use it in the component's slot. Is there any way of getting it work?
Example code:
Vue.component('test-component', {
template: '<div><slot></slot></div>',
computed: {
my_computed: function(){
return 2+3; // not defined in slot
}
}
})
<div id="app">
<test-component>
<span v-text="my_computed"></span>
</test-component>
</div>
See live example here, https://jsfiddle.net/gu9jh4n0/1/
The combination of the v-model and computed property makes your code robust and more reusable. Hope this article helps you to understand how to use two-way data binding in Vue. js by using the v-model directive and computed properties.
A computed property is cached, which implies that, for accessing data, the function runs just once if the value remains unchanged. Methods, on the other hand, need to run data properties checks every time, because they cannot tell otherwise if the values are changed inside the method property.
Yes, you can setup watcher on computed property, see the fiddle.
Computed properties are used to calculate the value of a property based on some other conditions. Watchers, on the other hand, are not primarily used for changing the value of a property; instead, they are used to notify you when the value has changed and let you perform certain actions based on these changes.
You could use a Scoped Slot to achieve that.
In your example, your component will look like this :
Vue.component('test-component', {
template: '<div><slot :computed="my_computed"></slot></div>',
computed: {
my_computed: function(){
return 2+3; // not defined in slot
}
}
});
And the main template will retrieve the slot's scope and use the computed :
<test-component>
<span slot-scope="data" v-text="data.computed"></span>
</test-component>
Live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With