在Vue + Vuex + Phaser反应式调用中丢失'this'范围

德里科

我试图使用Vue + Vuex制作游戏,但是在项目的中间,我意识到游戏中最互动的部分必须由Phaser制作,然后我决定将Phaser用作该部分,并保留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的这段代码中_newCreatureRX,VueX调用了该代码,当我尝试调用时_addCreature,收到一个错误消息,提示_addCreature未定义。console.log(this)示出的Vue对象。

我该如何使其正常工作?我是否必须以不同的方式组织项目?

菲尔

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

您可以函数显式绑定到正确的上下文

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章