This question already has an answer here:
I'm having trouble communicating with my data or methods with this code,
created() {
document.addEventListener( 'touchstart', function( e ) {
this.myData = e.changedTouches[ 0 ].screenY
}
}
I'm guessing that it's because of the function's scope, .this doesn't work inside the function, but then how do I communicate with my data or activate any methods outside of the event listener function then?
You are right this is happening because of
this
binding inside the callback which is not pointing the vue instanceTo solve this problem define a variable
var self = this
in the created hook pointing the vue instance and reference the data property usingself
inside the callbackNow since the callback has a closure over the variable
self
it references the vue instance when it gets invokedAs an alternative you can use arrow functions which bind
this
lexically as follows