Home >Web Front-end >JS Tutorial >Why is \'this\' Undefined in Vue.js Arrow Functions?
VueJS: Resolving the "this" Undefined Issue
Arrow functions can be a pitfall in VueJS, leading to unexpected undefined values. This is because arrow functions inherit the context of their parent, rather than binding to the Vue instance.
Lifecycle Hooks
When using arrow functions in lifecycle hooks like mounted, this does not refer to the Vue instance. Instead, it refers to the parent context, which is typically an HTML element or the Vue component that triggered the mounted hook.
mounted: () => { console.log(this); // undefined },
Computed Properties
Arrow functions in computed properties also lead to undefined values. As they inherit the parent context, this does not refer to the Vue instance.
computed: { foo: () => { return this.bar + 1; } },
This results in the error "Uncaught TypeError: Cannot read property 'bar' of undefined".
Solution
To resolve this, use regular functions or ECMAScript 5 function shorthands instead of arrow functions:
mounted: function () { console.log(this); },
mounted() { console.log(this); }
By using these methods, you can ensure that this always refers to the Vue instance, providing the expected behavior in lifecycle hooks and computed properties.
The above is the detailed content of Why is \'this\' Undefined in Vue.js Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!