It's important to note that the issue arises due to the binding of this
inside the callback function, which does not refer to the Vue instance.
To resolve this issue, you can create a variable var self = this
in the created hook to explicitly point to the Vue instance. Then, you can access data properties using self
within the callback function.
created() {
var self = this;
document.addEventListener('touchstart', function(e) {
self.myData = e.changedTouches[0].screenY;
})
}
By creating a closure over the self
variable, the callback function will correctly reference the Vue instance when executed.
Alternatively, you can utilize arrow functions, which maintain lexical binding of this
, like so:
created() {
document.addEventListener('touchstart', (e) => {
this.myData = e.changedTouches[0].screenY;
})
}