1

My method in vue looks like this :

methods: { 
    setDate: async function () {
        console.log(this.modal)
    }
}

I want to change it to an arrow function. I tried like this :

methods: { 
    setDate: async () => {
        console.log(this.modal)
    }
}

There exist error like this :

Cannot read property 'modal' of undefined

How can I solve this problem?

Ankit Kante
  • 2,029
  • 1
  • 19
  • 41
moses toh
  • 12,344
  • 71
  • 243
  • 443

3 Answers3

1

use function directly like

methods: { 
    async setDate() {
        console.log(this.modal)
    }
}
Vibha Chosla
  • 733
  • 5
  • 12
  • is there a difference between `async setDate() {` and `setDate: async function () {`? – moses toh Nov 21 '19 at 04:45
  • 1
    The former is [a newer syntax introduced in ECMAScript 2015](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions). So the only real difference is in terms of browser support – Michal Levý Nov 21 '19 at 08:09
1

You are facing this error because an arrow function wouldn't bind this to the vue instance for which you are defining the method. The same would happen if you were to define computed properties using an arrow function.

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.

You can read about it here.

tony19
  • 125,647
  • 18
  • 229
  • 307
haMzox
  • 2,073
  • 1
  • 12
  • 25
0

This link https://michaelnthiessen.com/this-is-undefined/ says the following:

"An arrow function uses what is called lexical scoping. We'll get into this more in a bit, but it basically means that the arrow function takes this from it's context.

If you try to access this from inside of an arrow function that's on a Vue component, you'll get an error because this doesn't exist!

So in short, try to avoid using arrow functions on Vue components. It will save you a lot of headaches and confusion."

RickL
  • 2,811
  • 3
  • 22
  • 35