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!