与vue和addEventListener中的数据或方法进行通信 [英] communicating with data or methods in vue and addEventListener

查看:946
本文介绍了与vue和addEventListener中的数据或方法进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用此代码与我的数据或方法进行通信时遇到问题,

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?

推荐答案

你是对的,因为回调内的这个绑定没有指向vue实例

You are right this is happening because of this binding inside the callback which is not pointing the vue instance

要解决这个问题,请定义一个变量 var self =这个在创建的钩子中指向vue实例并在回调中使用 self 引用data属性

To solve this problem define a variable var self = this in the created hook pointing the vue instance and reference the data property using self inside the callback

created() {
  var self = this;
  document.addEventListener( 'touchstart', function( e ) {
    self.myData = e.changedTouches[ 0 ].screenY
  }

现在,由于回调对变量 self 有一个闭包,它在调用时引用了vue实例

Now since the callback has a closure over the variable self it references the vue instance when it gets invoked

作为替代方案,你可以使用箭头函数来解释这个,如下所示

As an alternative you can use arrow functions which bind this lexically as follows

created() {
  document.addEventListener( 'touchstart', ( e ) => {
    this.myData = e.changedTouches[ 0 ].screenY
  }

这篇关于与vue和addEventListener中的数据或方法进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆