Home > Web Front-end > JS Tutorial > Why is \'this\' Undefined in Vue.js Arrow Functions?

Why is \'this\' Undefined in Vue.js Arrow Functions?

Linda Hamilton
Release: 2024-11-15 22:14:03
Original
964 people have browsed it

Why is

VueJS: Resolving the "this" Undefined Issue

Arrow functions can be a pitfall in VueJS, leading to unexpected undefined values. This is because arrow functions inherit the context of their parent, rather than binding to the Vue instance.

Lifecycle Hooks

When using arrow functions in lifecycle hooks like mounted, this does not refer to the Vue instance. Instead, it refers to the parent context, which is typically an HTML element or the Vue component that triggered the mounted hook.

mounted: () => {
  console.log(this); // undefined
},
Copy after login

Computed Properties

Arrow functions in computed properties also lead to undefined values. As they inherit the parent context, this does not refer to the Vue instance.

computed: {
  foo: () => { 
    return this.bar + 1; 
  } 
},
Copy after login

This results in the error "Uncaught TypeError: Cannot read property 'bar' of undefined".

Solution

To resolve this, use regular functions or ECMAScript 5 function shorthands instead of arrow functions:

mounted: function () {
  console.log(this);
},
Copy after login
mounted() {
  console.log(this);
}
Copy after login

By using these methods, you can ensure that this always refers to the Vue instance, providing the expected behavior in lifecycle hooks and computed properties.

The above is the detailed content of Why is \'this\' Undefined in Vue.js Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template