Home >Web Front-end >JS Tutorial >Why is \'this\' Undefined in Vue.js Components with Arrow Functions?
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" },
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; } }
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:
mounted: function () { console.log(this); }
mounted() { console.log(this); }
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!