Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use computed property in data in Vuejs

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'     }   } }) 
like image 610
Clinton Green Avatar asked Jun 01 '17 22:06

Clinton Green


People also ask

Can I use computed property in data Vue?

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.

Can you watch a computed value Vue?

Yes, you can setup watcher on computed property, see the fiddle.

Can I use computed in V model?

We can use this method to combine computed properties and the v-model in order to write the most robust code on Vue. js.


2 Answers

Unfortunately, it is impossible to use computed property in data because of component creation timing: data evaluates Before computed properties.

like image 100
Zvezdochka Avatar answered Oct 07 '22 17:10

Zvezdochka


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;     }   } }); 
like image 28
kevguy Avatar answered Oct 07 '22 17:10

kevguy