-1

Hi I am trying to use a fat arrow function as a method in a vuex component file:

methods : {
    method_1 : () => {console.log(this)}
}

this returns undefined, though if I use a function() { console.log(this) } it returns the current vue instance.

Why is this?

frank astin
  • 115
  • 10

1 Answers1

0

It's because the this keyword works differently in classic function and arrow functions.

Vue.js assumes you will use a classic function so they can control what is the value of this (which is the Vue instance)

What you need to do is either:

method_1 : function() { console.log(this) }

or

method_1() { console.log(this) }

but you cannot use an arrow function if you need the this keyword

Boris K
  • 1,469
  • 9
  • 29