我在 VueJS 中创建了一个新组件并定义了两个方法。 一种方法是action(vuex),另一种是常规方法。
actionTypes.js
const TOGGLE_PREVIEW = 'togglePreview';
组件
method: {
...mapActions([actionTypes.TOGGLE_PREVIEW]),
onClickPreview: () => {
this.togglePreview();
}
发生错误; 未捕获类型错误:无法读取未定义的属性“togglePreview”
。
最佳答案
创建 Vue 实例时,Vue 会代理实例上的数据、方法、 Prop 和注入(inject),以便于访问。它使用Function.prototype.bind来代理方法..
The
bind()
method creates a new function that, when called, has itsthis
keyword set to the provided value
但是这不适用于箭头函数,因为它们的作用域无法绑定(bind)并且它们继承其父级的作用域。因此,您的情况的解决方案是使用普通函数,以便它的 this
范围可以正确绑定(bind)到 Vue 实例。
methods: {
...mapActions([actionTypes.TOGGLE_PREVIEW]),
onClickPreview() {
this.togglePreview();
}
}
关于javascript - 如何修复VueJS中的 "this is undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357882/