自定义事件没有在 Vue 2 中传播。Vue 3 中是否有变化,因为如以下示例所示,自定义事件看起来像在组件链中冒泡:
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
防止
link to docs ,尽管它似乎并不表明它也会影响事件。它只是提到了属性,但事件是属性的一部分($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>
关于javascript - 自定义事件是否会在 Vue 3 中向上传播组件链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64613446/