I'm creating a component with Vue.js.
When I reference this
in any of the the lifecycle hooks (created
, mounted
, updated
, etc.) it evaluates to undefined
:
mounted: () => {
console.log(this); // logs "undefined"
},
The same thing is also happening inside my computed properties:
computed: {
foo: () => {
return this.bar + 1;
}
}
I get the following error:
Uncaught TypeError: Cannot read property 'bar' of undefined
Why is this
evaluating to undefined
in these cases?
You are using arrow functions.
The Vue Documentation clearly states not to use arrow functions on a property or callback.
Unlike a regular function, an arrow function does not bind
this
. Instead,this
is bound lexically (i.e.this
keeps its meaning from its original context).This logs the following object in the console:
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
Whereas... If we use a regular function (which we should on a Vue instance)
Logs the following object in the console:
hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}
Both of those examples use an arrow function
() => { }
, which bindsthis
to a context different from the Vue instance.As per the documentation:
In order to get the correct reference to
this
as the Vue instance, use a regular function:Alternatively, you can also use the ECMAScript 5 shorthand for a function: