Can a custom event be triggered from the directive inside the component it is attached to?
I tried following the example provided, but it didn't work as expected.
Example:
//Basic Directive
<script>
Vue.directive('foo', {
bind(el, binding, vnode) {
setTimeout(() => {
//vnode.context.$emit('bar'); <- this will trigger in parent
vnode.$emit('bar');
}, 3000);
}
});
</script>
//Basic Component
<template>
<button v-foo @bar="change">{{label}}</button>
</template>
<script>
export default{
data() {
return {
label: 'i dont work'
}
},
methods: {
change() {
this.label = 'I DO WORK!';
}
}
}
</script>
Any suggestions on how to make this work? Am I overlooking something?
JSFiddle: https://jsfiddle.net/0aum3osq/4/
Update 1:
After some investigation, I found that calling vnode.data.on.bar.fn();
(or fns()
in newer Vue versions) in the directive triggers the bar
event handler.
Update 2:
Temporary workaround:
/*temp. solution*/
var emit = (vnode, name, data) => {
var handlers = vnode.data.on;
if (handlers && handlers.hasOwnProperty(name)) {
var handler = handlers[name];
var fn = handler.fns || handler.fn;
if (typeof fn === 'function') {
fn(data);
}
}
}
//Basic Directive
<script>
Vue.directive('foo', {
bind(el, binding, vnode) {
setTimeout(() => {
emit(vnode, 'bar');
}, 3000);
}
});
</script>