Use computed property in data in Vuejs

前提是你 提交于 2019-12-05 13:14:21

问题


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'
    }
  }
})

回答1:


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;
    }
  }
});



回答2:


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




回答3:


  1. Computed is already accessible in the template using {{ }}.

  2. But you can use the

watch:{
  //your function here
}

instead of computed



来源:https://stackoverflow.com/questions/44318343/use-computed-property-in-data-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!