VueJS: why is this this undefined?

I am creating a component with Vue.js.

When I refer to this on any of the lifecycle hooks ( created , mounted , updated , etc.) it evaluates to undefined :

 mounted: () => { console.log(this); // logs "undefined" }, 

The same thing happens inside my computed properties:

 computed: { foo: () => { return this.bar + 1; } } 

I get the following error:

Uncaught TypeError: Cannot read the 'bar' property from undefined

Why does this evaluate undefined in these cases?

+8
javascript this vuejs2
source share
1 answer

Both examples use the arrow function () => { } , which associates this with a context other than the Vue instance.

According to the documentation :

Do not use arrow functions for instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod()) ). Since arrow functions are bound to the parent context, this will not be an instance of Vue, as youd expected, and this.myMethod will be undefined.

To get the correct reference to this as an instance of Vue, use a regular function:

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

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

 mounted() { console.log(this); } 
+25
source share

All Articles