简体   繁体   中英

How i can emit event from directive by click outside of element?

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

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:

  template:'<button type="button" @click="clickEvent" v-click-outside>test</button>',
  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 -

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM