【发布时间】:2019-11-05 04:37:36
【问题描述】:
我无法从根 Vue 实例中的子组件接收任何事件。
我有一个简单的子组件,它在单击或安装时会发出“hello”事件:
<template>
<div v-on:click="clicked"></div>
</template>
<script>
export default {
name: 'ChildComponent',
mounted() {
this.$emit('hello');
},
methods: {
clicked() {
this.$emit('hello');
}
}
};
</script>
在我的根 Vue 实例中,我已经尝试了一切来接收事件,但似乎没有一个处理程序正在接收事件。我不确定我做错了什么。
const comp = () => import('./components/SomeVueWhichHasChild.vue');
const v = new Vue({
store,
render: h => h(comp, {
on: {
hello: () => {
console.log('VUE INSTANCE HELLO');
}
},
nativeOn: {
hello: () => {
console.log('NATIVE HELLO');
}
}
}),
});
v.$on('hello', () => {
console.log('ON HELLO');
});
v.$mount('#app');
【问题讨论】:
-
您确定调用了子组件中的
clicked()方法吗? div 是空的,所以我认为它没有任何大小;你怎么能点击它? -
是的,这只是这篇文章的示例代码。例如,ChildComponent 的父级可以接收事件并将其发送给其父级,依此类推,直到它到达根。就我而言,我正在编写一个插件并且无法控制组件的层次结构。我需要从我的插件组件向根 Vue 实例发出一个事件。到目前为止,我提供的答案对我来说效果很好。
标签: vue.js