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" }
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; } }
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); }
ES5 Shorthand:
mounted() { console.log(this); }
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!