自定义事件没有在Vue 2中传播。Vue3是否发生了变化,因为如下例所示,它看起来像是组件链中的自定义事件:
const Comp1 = {
template: `
<button @click="this.$emit('my-event')">click me</button>
`
}
const Comp2 = {
components: {
Comp1
},
template: `
<Comp1/>
`
}
const HelloVueApp = {
components: {
Comp2
},
methods: {
log() {
console.log("event handled");
}
}
}
Vue.createApp(HelloVueApp).mount('#hello-vue')
<script src="https://unpkg.com/vue@next"></script>
<div id="hello-vue" class="demo">
<Comp2 @my-event="log"/>
</div>
是的,默认情况下,它们现在在VUE v3中失败
您需要定义inheritAttrs: false
以防止该
链接到文档,尽管它似乎并没有表明它也会影响事件。它只是提到属性,但事件是属性的一部分($attrs
(。
const Comp1 = {
template: `
<button @click="this.$emit('my-event')">click me</button>
`
}
const Comp2 = {
components: {
Comp1
},
template: `
<Comp1/>
`,
inheritAttrs: false
}
const HelloVueApp = {
components: {
Comp2
},
methods: {
log() {
console.log("event handled APP");
}
}
}
Vue.createApp(HelloVueApp).mount('#hello-vue')
<script src="https://unpkg.com/vue@next"></script>
<div id="hello-vue" class="demo">
<Comp2 @my-event="log"/>
</div>
您必须将事件处理到Comp2:中
<Comp1 @my-event="this.$emit('my-event')"/>