0

I have this code in my mounted function :

 mounted () {
    document.addEventListener('keydown', function (e) {
      switch (e.keyCode) {
        case 37 :
          alert(this.indexPictures)
          break
      }
    })
  }

My data value :

  data: function () {
    return {
      indexPictures: this.index,
    }
  },

My result : undefined

I don't know why but I can't get value in data function and this is the same problem, from methods access. My result : is not a function

Do you have any ideas ?

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Florian
  • 11
  • 3
  • As you already have a `index` property then I don't think assigning it to an another variable (`indexPictures`) make sense. You can directly access `this.index` wherever required. – Debug Diva Sep 28 '22 at 04:37

1 Answers1

-1

Not sure what this.index is but I will assume it is a prop or something similar.

Try removing the keyword function from the addEventListener.

 mounted () {
    document.addEventListener('keydown', (e)=> {
      switch (e.keyCode) {
        case 37 :
          alert(this.indexPictures)
          break
      }
    })
  }

It is not particularly relevant to the problem, but remove the function keyword from data as well:

data() {
    return {
      indexPictures: this.index,
    }
  },

The keyword function changes the scope, meaning this is bind to the function itself (in your case the callback). When you use an arrow function this keyword will be the same as in mounted - which means you can access your data.

From MDN docs:

Perhaps the greatest benefit of using Arrow functions is with methods like setTimeout() and EventTarget.prototype.addEventListener() that usually require some kind of closure, call, apply or bind to ensure that the function is executed in the proper scope.

Keep in mind if this is a part of a component it is a good idea to remove that listener before destroying the component.

Zarko
  • 314
  • 2
  • 7