1

我使用 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);
    },
}

wherechampionshipschampionship_id是全局数据。

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

现在,我简化,我写:

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

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

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

4

2 回答 2

3

使用箭头函数,让你this成为真正的 Vue 实例:

mounted () {
    this.$nextTick(() => {
        Vue.vueDragula.eventBus.$on(
            'drop',
            args => console.log(this.championship)
        );
    })
}
于 2017-03-16T17:09:49.723 回答
2

this在 drop 事件函数中不再引用 Vue 实例。尝试在调用之前thismounted函数中设置对的引用$nextTick

mounted: function () {
  let vm = this;
  this.$nextTick(function () {
    Vue.vueDragula.eventBus.$on(
      'drop',
      function (args) {
        console.log(vm.championship);
      }
    );
  }
}
于 2017-03-16T17:09:17.040 回答