Use computed property in data in Vuejs

2019-04-06 04:12发布

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

2条回答
爷的心禁止访问
2楼-- · 2019-04-06 04:48

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

查看更多
Evening l夕情丶
3楼-- · 2019-04-06 04:57

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;
    }
  }
});
查看更多
登录 后发表回答