简体   繁体   English

如何在 Vue 自定义指令中添加事件监听器?

[英]How can i add event listener in Vue customized directive?

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:我正在使用 Vue2.x,我想通过使用自定义指令添加事件侦听器,但是在 vue1.x 中我可以使用以下代码片段:

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.但是在 vue2.x 中,我发现 'this' 总是未定义的,我无法弄清楚如何获取 vm (Vue Instance) 对象。 I've tried all the passed parameter list on documentation .我已经尝试了文档中所有传递的参数列表。

Does anyone know how to get access to the vm object?有谁知道如何访问 vm 对象?

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:有一些不同之处,您可以在此 CodePen中看到完整的工作示例(尽管稍作调整),但我将在这里详细说明:

Your references to this are invalid because in the directive's context this refers to the window .您对this的引用是无效的,因为在指令的上下文中this指的是window Instead of these references:而不是这些参考:

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

you should be consuming the three arguments passed to bind() :您应该使用传递给bind()的三个参数:

  1. el - the DOM element el - DOM 元素
  2. binding - binding object for the directive's metadata, including expression binding - 指令元数据的绑定对象,包括expression
  3. vnode - VNode object - its context property is the Vue instance vnode - VNode 对象 - 它的context属性是 Vue 实例

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 .最后,附注:您的事件侦听器不会导致任何事情发生,因为您单击元素会触发一个stopProp函数(该函数已从您的代码段中排除),该函数可能会调用stopPropagation()但随后您尝试在body

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM