简体   繁体   中英

How to fix “this is undefined” in VueJS?

I've created a new component in VueJS and defined two methods. One method is action(vuex) and another one is regular method.

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 .

When a Vue instance is created Vue proxies data, methods, props and injections on the instance for easy access. To proxy methods it uses Function.prototype.bind ..

The bind() method creates a new function that, when called, has its this keyword set to the provided value

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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