I cannot receive any events from a child component in the root vue.js instance.
there is a simple child component which emits a ‘hello’ event when clicked or mounted:
<template>
<div v-on:click=”clicked”></div>
</template>
<script>
export default {
name: ‘ChildComponent’,
mounted() {
this.$emit(‘hello’);
},
methods: {
clicked() {
this.$emit(‘hello’);
}
}
};
</script>
In my root vue.js instance I’ve tried everything to receive the event, but none of the handlers seem to be receiving the event. I’m not sure what I’m doing wrong.
const comp = () => import(‘./components/SomeVueWhichHasChild.vue’);
const v = new Vue({
store,
render: h => h(comp, {
on: {
hello: () => {
console.log(‘vue.js INSTANCE HELLO’);
}
},
nativeOn: {
hello: () => {
console.log(‘NATIVE HELLO’);
}
}
}),
});
v.$on(‘hello’, () => {
console.log(‘ON HELLO’);
});
v.$mount(‘#app’);
Solution :
Seems like this is a dup of:
How to bubble events on a component subcomponent chain with vue.js js 2?
Only a direct parent of a component can listen for events. I used native JS events instead:
this.$el.dispatchEvent(new CustomEvent(‘hello’, {
detail: { … },
bubbles: true,
composed: true
}));
Solution 2:
As @Decade Moon said, the div should have some content to be able to be clickable. For example:
<div v-on:click=”clicked”>Test content</div>
You can check my demo on Codepen