communicating with data or methods in vue and addE

2019-04-17 02:44发布

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?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-17 03:02

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

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
  }

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
  }
查看更多
登录 后发表回答