1

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?

tony19
  • 125,647
  • 18
  • 229
  • 307
CALTyang
  • 1,128
  • 1
  • 8
  • 13

1 Answers1

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.

Rommel Santor
  • 1,021
  • 7
  • 10
  • I just try to add click-outside event to a div.Like this question [http://stackoverflow.com/questions/36170425/detect-click-outside-element](Detect click outside element).But I found that the $emit callback doesn't work.Anyway I found the [vue-clickaway](https://github.com/simplesmiler/vue-clickaway) project.Thanks a lot. – CALTyang Dec 27 '16 at 07:51