最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论