Vue.js - Emit event from directive

后端 未结 7 472
北海茫月
北海茫月 2021-02-02 12:37

Is it possible to emit a custom event from the directive in the component to which this directive is attached.

I was expecting it to work as described

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 13:20

    You can emit custom native javascript events. Create a directive that dispatches an event from the node, using node.dispatchEvent

    let handleOutsideClick;
    Vue.directive('out-click', {
        bind (el, binding, vnode) {
    
            handleOutsideClick = (e) => {
                e.stopPropagation()
                const handler = binding.value
    
                if (el.contains(e.target)) {
                    el.dispatchEvent(new Event('out-click')) <-- HERE
                }
            }
    
            document.addEventListener('click', handleOutsideClick)
            document.addEventListener('touchstart', handleOutsideClick)
        },
        unbind () {
            document.removeEventListener('click', handleOutsideClick)
            document.removeEventListener('touchstart', handleOutsideClick)
        }
    })
    

    Which can be used like this

    h3( v-out-click @click="$emit('show')" @out-click="$emit('hide')" )
    

提交回复
热议问题