在VueJS中检索计算属性

时间:2017-03-16 17:05:45

标签: vue.js computed-properties

我使用Vue-Dragula进行跌落。当我放弃时,它会触发方法:

mounted: function () {
    this.$nextTick(function () {
        Vue.vueDragula.eventBus.$on(
            'drop',
            function (args) {
                console.log(this.championship);
            }
        );

}

现在this.championship是一个计算属性:

computed: {
    championship(){
        return this.championships.find((elem) => elem.championship == this.championship_id);
    },
}

其中championshipschampionship_id是全局数据。

console.log(this.championship);返回undefined

现在,我简化了,我写道:

computed: {
    championship(){
        return 2;
    },
}

console.log(this.championship);继续undefined

我的代码有什么问题???

2 个答案:

答案 0 :(得分:3)

使用箭头功能,以便this成为实际的Vue实例:

mounted () {
    this.$nextTick(() => {
        Vue.vueDragula.eventBus.$on(
            'drop',
            args => console.log(this.championship)
        );
    })
}

答案 1 :(得分:2)

this在drop事件函数中不再引用Vue实例。在this来电之前,尝试在mounted函数中设置对$nextTick的引用:

mounted: function () {
  let vm = this;
  this.$nextTick(function () {
    Vue.vueDragula.eventBus.$on(
      'drop',
      function (args) {
        console.log(vm.championship);
      }
    );
  }
}