【问题标题】:retrieve a computed property in VueJS在 VueJS 中检索计算属性
【发布时间】:2017-08-08 00:08:17
【问题描述】:

我使用 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

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

【问题讨论】:

标签: vue.js computed-properties


【解决方案1】:

使用箭头函数,这样您的 this 将成为实际的 Vue 实例:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 2021-05-16
      • 1970-01-01
      • 2020-01-23
      • 2020-02-05
      • 2018-02-21
      • 2018-01-02
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多