简体   繁体   English

我如何通过在元素外部单击来从指令中发出事件?

[英]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:从 v-click-outside="clickEvent" 我得到:

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 )不支持驼峰案例自定义事件(始终使用 kebab 案例 - https://v2.vuejs.org/v2/guide/components-custom-events.html#Event-Names

Check out the following fiddle - https://jsfiddle.net/chrismarx/gvrsmj1y/7/ 查看以下小提琴 - 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.根组件必须定义 parentClickEvent 方法,因为事件是从组件 a 发出的。 You also need to emit the event from within component-a您还需要从 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 )或使用 $root 对象在同一级别发出和侦听事件( this.$root.$emit 在 Vue 中不起作用


2. The $emit call should broadcast a kebab cased event, otherwise the event won't get picked up - 2. $emit 调用应该广播一个 kebab cased 事件,否则该事件将不会被接收 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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