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

Why is \"this\" Undefined in Vue.js Components and Computed Properties Using Arrow Functions?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-18 12:05:02768browse

Why is

Why is the Reference to "this" Undefined in Vue.js Components and Computed Properties?

In Vue.js, defining components and utilizing computed properties involves working with the 'this' keyword. However, developers often encounter the issue where 'this' evaluates to 'undefined' in certain scenarios. This article aims to clarify why this occurs and provide solutions.

When using arrow functions (e.g., () => {}) in lifecycle hooks (such as mounted and updated) or computed properties, the value of 'this' may differ from the intended Vue instance. The Vue.js documentation explicitly advises against using arrow functions in such contexts. Instead, developers should employ regular functions or the ECMAScript 5 shorthand syntax to ensure 'this' references the Vue instance appropriately.

Consider the example of a component:

mounted: () => {
  console.log(this); // returns "undefined"
},

In this case, the arrow function () => {} binds 'this' to a different context outside the Vue component. Consequently, accessing properties or methods using 'this' outside the function will fail.

Similarly, in a computed property:

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

The computed property's value evaluation using the arrow function () => {} will also lead to 'this' being undefined. This results in the error "Cannot read property 'bar' of undefined."

To rectify this issue, regular JavaScript functions or the ECMAScript 5 shorthand can be used:

mounted: function () {
  console.log(this); // correctly logs the Vue instance
}
mounted() {
  console.log(this); // also correctly logs the Vue instance
}

These examples demonstrate how regular functions or ECMAScript 5 shorthand appropriately bind 'this' to the Vue component instance, resolving the issue where 'this' evaluates to 'undefined.'

The above is the detailed content of Why is \"this\" Undefined in Vue.js Components and Computed Properties Using 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