How can I use a computed property in the data or emit it via bus?
I have the following vue instance, but myComputed is always undefined but computedData is working correctly.
var vm = new Vue({ data(){ return{ myComputed: this.computedData } }, computed: { computedData(){ return 'Hello World' } } })
In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.
Yes, you can setup watcher on computed property, see the fiddle.
We can use this method to combine computed properties and the v-model in order to write the most robust code on Vue. js.
Unfortunately, it is impossible to use computed property in data because of component creation timing: data evaluates Before computed properties.
To make things as simple as possible, just do the work in watcher, unless you want to emit the changes to different components or there're a lot of variables you want to notify, then you may have to use Vuex or the event bus:
var vm = new Vue({ data(){ return{ myComputed: '', computedData: 'Hello World' } }, created() { this.myComputed = this.computedData; }, watch: { computedData() { this.myComputed = this.computedData; } } });
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