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

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

Susan Sarandon
Release: 2024-11-28 14:06:14
Original
686 people have browsed it

Why is

Unexpected Undefined Value for "this" in Vue.js Components

When constructing Vue.js components, accessing "this" within lifecycle hooks or computed properties can yield unexpected "undefined" results. Arrow functions, denoted by the syntax "() => {}", alter the binding of "this" outside of the Vue instance context.

Lifecycle Hooks

In the provided example:

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

The arrow function binds "this" to a scope outside the Vue instance, leading to an "undefined" evaluation.

Computed Properties

Similarly, within computed properties:

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

The arrow function creates a different binding for "this," resulting in the "Cannot read property 'bar' of undefined" error.

Solution

To resolve this issue and ensure the correct reference to "this" as the Vue instance, consider using the following techniques:

  1. Regular Function: Use a regular function syntax, as demonstrated by:
mounted: function () {
  console.log(this);
}
Copy after login
  1. ECMAScript 5 Shorthand: Alternatively, you can use the ECMAScript 5 function shorthand:
mounted() {
  console.log(this);
}
Copy after login

By employing these methods, you can establish the proper binding of "this" within Vue.js components, ensuring accessibility to the component's properties and methods as expected.

The above is the detailed content of Why is \'this\' Undefined in Vue.js Components with 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