Sometimes, we want to fix “this” being undefined with Vue.js.
In this article, we’ll look at how to fix “this” being undefined with Vue.js.
How to fix “this” being undefined with Vue.js?
To fix “this” being undefined with Vue.js, we should use regular functions for hooks, computed properties, and methods.
For instance, we write
export default {
//...
mounted() {
console.log(this);
},
//...
};
to add the mounted
hook by setting mounted
to a regular function.
As a result, this
will refer to the current Vue component instance instead of undefined
.
Conclusion
To fix “this” being undefined with Vue.js, we should use regular functions for hooks, computed properties, and methods.