javascript - 如何修复VueJS中的 "this is undefined"?

标签 javascript vue.js methods

我在 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 its this 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/

相关文章:

javascript - 将 $(this) 传递到设置的超时函数中?

JavaScript 中的 Java byteArray 等价物

javascript - 如果输入字段聚焦,如何更改父级的 css 类

javascript - vue-cli3 eslint vue/script-indent 与编译器冲突

vue.js - 当 Vuejs 中的 Prop 值发生变化时,DOM 不会更新

vue.js - [Vue 警告] : Failed to mount component: template or render function not defined?

java - 方法,较小值

Python 装饰类不允许方法调用。为什么?

javascript - 下拉选择后显示表单以编辑表中的 mysql 数据

javascript - 没有大括号的 ES6 getter/方法