簡體   English   中英

我如何通過在元素外部單擊來從指令中發出事件?

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

我不明白如何從指令中發出事件

這是我嘗試調用方法的模板:

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

從 v-click-outside="clickEvent" 我得到:

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

我的代碼:

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)
  },
})

我得到:

Invalid handler for event "emitedEvent": got undefined

我懷疑您遇到的問題主要基於兩個問題:

  1. 您定義函數的級別
  2. 不支持駝峰案例自定義事件(始終使用 kebab 案例 - https://v2.vuejs.org/v2/guide/components-custom-events.html#Event-Names

查看以下小提琴 - https://jsfiddle.net/chrismarx/gvrsmj1y/7/

請注意,使用此模板:

  template:'<button type="button" @click="clickEvent" v-click-outside>test</button>',
  1. 根組件必須定義 parentClickEvent 方法,因為事件是從組件 a 發出的。 您還需要從 component-a 中發出事件
 template:'<button type="button" @click="clickEvent" v-click-outside>test</button>',

或使用 $root 對象在同一級別發出和偵聽事件( this.$root.$emit 在 Vue 中不起作用


2. $emit 調用應該廣播一個 kebab cased 事件,否則該事件將不會被接收 -

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM