Vue.js - Emit event from directive
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:
<button v-foo @bar="bar(1, $event, 2)">{{label}}</button>
...
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)
Your solution was not working for me. Indeed vnode.data.on was always undefined
What worked to trigger an event was
vnode.child.$emit('myevent');
Hope this helps.