在 Vue + Vuex + Phaser 反应调用中丢失 'this' 范围
Losing 'this' scope in a Vue + Vuex + Phaser reactive call
我曾尝试使用 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 的这段代码中,_newCreatureRX
被 VueX 调用,当我尝试调用 _addCreature
时,我收到一条错误消息,提示 _addCreature
未定义。 console.log(this)
显示一个 Vue 对象。
如何让它正常工作?我必须以不同的方式构建我的项目吗?
store.watch
方法不会在原来的上下文中执行回调函数,所以this
是不正确的。
您可以显式 bind 函数到正确的上下文
store.watch(this._newCreatureGetter, this._newCreatureRX.bind(this))
我曾尝试使用 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 的这段代码中,_newCreatureRX
被 VueX 调用,当我尝试调用 _addCreature
时,我收到一条错误消息,提示 _addCreature
未定义。 console.log(this)
显示一个 Vue 对象。
如何让它正常工作?我必须以不同的方式构建我的项目吗?
store.watch
方法不会在原来的上下文中执行回调函数,所以this
是不正确的。
您可以显式 bind 函数到正确的上下文
store.watch(this._newCreatureGetter, this._newCreatureRX.bind(this))