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