-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.