Vue.js - Emit event from directive

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

    So the solution I am using in Vue 2+ (considering there were no answers so far):

    In directive add method:

    var emit = (vnode, name, data) => {
      var handlers = (vnode.data && vnode.data.on) ||
        (vnode.componentOptions && vnode.componentOptions.listeners);
    
      if (handlers && handlers[name]) {
        handlers[name].fns(data);
      }
    }
    

    And call it this way:

    bind(el, binding, vnode) {
      emit(vnode, 'bar' , {some: 'event', data: 'here'});
    }
    

    The benefits of an approach:

    1 Keep the same code-style in your project, meaning that every handler can be declared as
    v-on:handler_name and be handled in meaningful (for developer) way. Other solutions, like sending callback as parameter, are sometimes confusing and not obvious without digging into documentation/code.

    2 Using built-in events system also allows to gracefully handle event objects. For example, this code will work perfectly fine:

    
    ...
    methods: {
      bar(one, event, two) { console.log(one, event, two); }
    } 
    

    EDIT:

    In v2.1+ you can use this inside directive binding:

    vnode.context.$emit(eventname)
    

提交回复
热议问题