Home > Web Front-end > JS Tutorial > Why Does \'this\' Become Undefined in Vue.js Lifecycle Hooks and Computed Properties?

Why Does \'this\' Become Undefined in Vue.js Lifecycle Hooks and Computed Properties?

DDD
Release: 2024-11-28 04:58:10
Original
767 people have browsed it

Why Does

VueJS: "this" Undefined in Lifecycle Hooks and Computed Properties

In Vue.js, you may encounter situations where accessing the "this" keyword within lifecycle hooks or computed properties returns "undefined." This occurs when arrow functions are used.

Cause:

Arrow functions () => {} bind the "this" keyword to the context outside the Vue instance. This means that "this" within an arrow function refers to the parent scope, not the Vue instance itself.

Example 1:

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

In this example, the arrow function used for the "mounted" hook doesn't bind "this" to the Vue instance.

Example 2:

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

Here, the computed property uses an arrow function, which causes the reference to "this.bar" to evaluate to undefined, resulting in the error "Cannot read property 'bar' of undefined."

Solution:

To resolve this issue and access the correct reference to "this," use regular functions or the ES5 shorthand:

Regular Function:

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

ES5 Shorthand:

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

By using these approaches, you ensure that "this" refers to the Vue instance within lifecycle hooks and computed properties.

The above is the detailed content of Why Does \'this\' Become Undefined in Vue.js Lifecycle Hooks and Computed Properties?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template