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?
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()
:
el
- the DOM element binding
- binding object for the directive's metadata, including expression
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.