javascript - How can i add event listener in Vue customized directive? - Stack Overflow

I'm using Vue2.x and I want to add a event listener by using customising directives, however in vu

I'm using Vue2.x and I want to add a event listener by using customising directives, however in vue1.x I can use the following code snippet:

Vue.directive('demo',{
  bind () {
    let self  = this
    this.event = function (event) {
      self.vm.$emit(self.expression, event)
    }
    this.el.addEventListener('click', this.stopProp)
    document.body.addEventListener('click', this.event)
  }
})

but in vue2.x, I found that 'this' is always undefined, and I cannot figure out how to get the vm (Vue Instance) object. I've tried all the passed parameter list on documentation.

Does anyone know how to get access to the vm object?

I'm using Vue2.x and I want to add a event listener by using customising directives, however in vue1.x I can use the following code snippet:

Vue.directive('demo',{
  bind () {
    let self  = this
    this.event = function (event) {
      self.vm.$emit(self.expression, event)
    }
    this.el.addEventListener('click', this.stopProp)
    document.body.addEventListener('click', this.event)
  }
})

but in vue2.x, I found that 'this' is always undefined, and I cannot figure out how to get the vm (Vue Instance) object. I've tried all the passed parameter list on documentation.

Does anyone know how to get access to the vm object?

Share Improve this question edited Jul 13, 2022 at 22:57 tony19 139k23 gold badges277 silver badges347 bronze badges asked Dec 27, 2016 at 1:47 CALTyangCALTyang 1,2682 gold badges9 silver badges13 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

There are a few differences, and you can see a full, working example of your snippet (though tweaked a little) at this CodePen, but I'll elaborate here:

Your references to this are invalid because in the directive's context this refers to the window. Instead of these references:

this.event = ...
// ...
self.vm.$emit()
// ...
self.expression

you should be consuming the three arguments passed to bind():

  1. el - the DOM element
  2. binding - binding object for the directive's metadata, including expression
  3. vnode - VNode object - its context property is the Vue instance

With those in hand those three lines above would then correspond with:

el.event = ...
// ...
vnode.context.$emit()
// ..
binding.expression

Finally, a side note: your event listeners would cause nothing to happen because your click on the element triggers a stopProp function (that is excluded from your snippet), which presumably calls stopPropagation() but then you attempt to catch the propagated event on the body.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744667951a4586866.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信