Vue.js - Emit event from directive

后端 未结 7 462
北海茫月
北海茫月 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:28

    I know it is an old issue, but if someone has problems with this and it is not working. You can use use javascript custom events events.

        vue.directive('click',{bind(el, binding, vnode) {
            el.addEventListener('click', (e)=>{
                const event = new CustomEvent('customevent', {detail: {
                                                              custom: "data", 
                                                              can: "be", 
                                                              in: "detail property"}, bubbles: true});
                el.dispatchEvent(event);
            })
        }
    })
    

    now i can use it like

    hello world

    i do not have to set $event because the default is standard emitted as last param. this event has a detail property, which contains your custom data in this case this object:

    {custom: "data", 
     can: "be", 
     in: "detail property"}
    

    src https://github.com/vuejs/vue/issues/7147

提交回复
热议问题