Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  43] [ 6]  / answers: 1 / hits: 60660  / 7 Years ago, fri, may 12, 2017, 12:00:00

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?


More From » vue.js

 Answers
22

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);
}

[#57812] Wednesday, May 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;