简体   繁体   English

如何在VueJS中修复“这是未定义的”?

[英]How to fix “this is undefined” in VueJS?

I've created a new component in VueJS and defined two methods. 我在VueJS中创建了一个新组件并定义了两个方法。 One method is action(vuex) and another one is regular method. 一种方法是动作(vuex),另一种方法是常规方法。

actionTypes.js actionTypes.js

const TOGGLE_PREVIEW = 'togglePreview';

component 零件

method: {
  ...mapActions([actionTypes.TOGGLE_PREVIEW]),
  onClickPreview: () => {
    this.togglePreview();
  }

It occurred an error; 它出错了; Uncaught TypeError: Cannot read property 'togglePreview' of undefined . Uncaught TypeError: Cannot read property 'togglePreview' of undefined

When a Vue instance is created Vue proxies data, methods, props and injections on the instance for easy access. 创建Vue实例时,Vue会在实例上代理数据,方法,道具和注入,以便于访问。 To proxy methods it uses Function.prototype.bind .. 要代理方法,它使用Function.prototype.bind ..

The bind() method creates a new function that, when called, has its this keyword set to the provided value bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值

However this doesn't work on arrow functions since their scope cannot be bound and they inherit their parent's scope. 但是这对箭头函数不起作用,因为它们的作用域不能被绑定,并且它们继承了它们的父作用域。 So the solution in your case is to use a normal function instead so that it's this scope can be correctly bound to the Vue instance. 因此,在您的情况下,解决方案是使用普通函数,以便可以this范围正确绑定到Vue实例。

methods: {
  ...mapActions([actionTypes.TOGGLE_PREVIEW]),
  onClickPreview() {
    this.togglePreview();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM