0

I can't understand how to emit event from directive

This is my template where i try to call method :

<tooltip v-click-outside="clickEvent" v-on:emitedEvent="clickEvent"></tooltip>

From v-click-outside="clickEvent" i got:

Property or method "clickEvent" is not defined on the instance but referenced during render.

My code:

export default {
  data() {
    return {
    }
  },
  methods: {
    clickEvent: function () {
      console.log('click')
    }
  },
}
Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.event = function (event) {
      if (!(el.contains(event.target))) {
          vnode.context.$emit('emitedEvent')
      }
    }
    document.addEventListener('click', el.event)
  },
  unbind: function (el) {
    document.removeEventListener('click', el.event)
  },
})

I get:

Invalid handler for event "emitedEvent": got undefined
Alexandr
  • 115
  • 1
  • 5
  • Possible duplicate of [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Pogrindis Jan 08 '19 at 10:30

1 Answers1

0

I suspect the problems you're encountering are primarily based on two problems:

  1. the level at which you're defining the functions
  2. camel case custom events are not supported (always use kebab case - https://v2.vuejs.org/v2/guide/components-custom-events.html#Event-Names)

Check out the following fiddle - https://jsfiddle.net/chrismarx/gvrsmj1y/7/

Note that using this template:

<div id="app">
  <h2>directive test</h2>
  <component-a v-on:emited-event="parentClickEvent"></component-a> 
</div>
  1. The root component has to define the parentClickEvent method, since the event is being emitted from component-a. You also need to emit the event from within component-a
  template:'<button type="button" @click="clickEvent" v-click-outside>test</button>',

or use the $root object for emitting and listening for events at the same level ( this.$root.$emit not working in Vue )


2. The $emit call should broadcast a kebab cased event, otherwise the event won't get picked up -
tony19
  • 125,647
  • 18
  • 229
  • 307
chrismarx
  • 11,488
  • 9
  • 84
  • 97