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 01 Answer
Reset to default 5There 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()
:
el
- the DOM elementbinding
- binding object for the directive's metadata, includingexpression
vnode
- VNode object - itscontext
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条)