Home  >  Article  >  Web Front-end  >  Why is \"this\" Undefined in Vue.js Arrow Functions?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 22:14:03881browse

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
},

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; 
  } 
},

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);
},
mounted() {
  console.log(this);
}

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!

Statement:
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