Categories
Vue Answers

How to fix “this” being undefined with Vue.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *