VueJS: why is “this” undefined?

Both of those examples use an arrow function () => { }, which binds this to a context different from the Vue instance.

As per the documentation:

Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.

In order to get the correct reference to this as the Vue instance, use a regular function:

mounted: function () {
  console.log(this);
}

Alternatively, you can also use the ECMAScript 5 shorthand for a function:

mounted() {
  console.log(this);
}

Leave a Comment