mar*_*lin 5 javascript vue.js vuejs3
自定义事件没有在 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')Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@next"></script>
<div id="hello-vue" class="demo">
<Comp2 @my-event="log"/>
</div>Run Code Online (Sandbox Code Playgroud)
您需要定义inheritAttrs: false以防止这种情况
链接到 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')Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@next"></script>
<div id="hello-vue" class="demo">
<Comp2 @my-event="log"/>
</div>Run Code Online (Sandbox Code Playgroud)