【问题标题】:Losing 'this' scope in a Vue + Vuex + Phaser reactive call [duplicate]在 Vue + Vuex + Phaser 反应式调用中丢失“this”范围[重复]
【发布时间】:2017-06-07 12:03:28
【问题描述】:

我曾尝试使用 Vue + Vuex 制作游戏,但在项目进行中,我意识到必须使用 Phaser 制作游戏中最具交互性的部分,然后我决定使用 Phaser 来制作该部分并保留UI 的 Vue + Vuex。

在我尝试在 Phaser 中从 Vuex 获取第一个数据之前,一切都比预期的要好,问题是我失去了当前对象的范围。

我正在使用store.watch(); 获取更改,但是当我尝试调用其他函数时出现错误。

import store from '../vuex/store';
import Creature from './Creature';
const creatures = [];
export default {
  create() {
    store.watch(this._newCreatureGetter, this._newCreatureRX);
    for (const creature of this._creaturesGetter()) {
      this._addCreature(creature);
    }
  },
  _addCreature(creature) {
    creatures.push(new Creature(this.game, creature));
  },
  _newCreatureGetter() {
    return store.state.newCreature;
  },
  _newCreatureRX(newCreature) {
    console.log(this);
    this._addCreature(newCreature);
  },
};

在 Phaser 的这段代码中,VueX 调用了 _newCreatureRX,当我尝试调用 _addCreature 时,我收到一条错误消息,指出未定义 _addCreatureconsole.log(this) 显示了一个 Vue 对象。

如何让它正常工作?我必须以不同的方式构建我的项目吗?

【问题讨论】:

    标签: javascript ecmascript-6 vue.js phaser-framework vuex


    【解决方案1】:

    store.watch方法不会在原始上下文中执行回调函数,这就是this不正确的原因。

    你可以明确地bind函数到正确的上下文

    store.watch(this._newCreatureGetter, this._newCreatureRX.bind(this))
    

    【讨论】:

    • 成功了!谢谢!我不知道我可以使用 .bind(this) 发送回调。现在很有意义!
    • 很容易错过。问题是因为在 Vue.js 中,它通过cb.call(vm, watcher.value) 执行回调,其中vmVue 实例。见github.com/vuejs/vue/blob/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    相关资源
    最近更新 更多