为什么组件不响应自定义事件



我在main2.vue中发出一个名为emit-event-main2-计数器的事件

为什么Bottom.vue中的数据cntr不会更新?

App.vue

<template>
<div class="app">
<Main2 />
<Bottom/>
</div>
</template>
<script>
import Main2 from "./components/Main2";
import Bottom from "./components/Bottom";
export default {
components: {
Main2,
Bottom
},
}
</script>
<style scoped>
h1 {
color: red;
}
</style>

Main2.vue

<template>
<div>
main2 template <span class="text1">{{message}}</span>
<button type="button" v-on:click="btnClickButton">my click</button>
<div>{{counter}}</div>
</div>
</template>
<script>
import appInput from "./appInput.vue";
export default {
data: () => {
return {
message: "theText",
counter: 0,
}
},
components: {
appInput,
},
methods: {
btnClickButton(e) {
this.$root.$emit('emit-event-main2-counter', this.counter)
console.log('button');
this.counter +=1;
}
}
}
</script>
<style scoped>
.text1 {
color:red;
}
.text2 {
color:blue;
}
</style>

底部.vue

<template>
<div  class="Bottom" v-on:emit-event-main2-counter="cntr = $event">
bottom text and cntr ({{cntr}})
</div>
</template>
<script>
export default {
data: () => {
return {
cntr: 0
}
},
}
</script>
<style scoped>
</style>

您可以从参数为this.counterMain2向父级发送事件,并且在父级中接收该事件并通过props将其传递给Bottom

Main2:中

this.$emit("emit-event-main2-counter",this.counter);

parent组件中:

<template>
<Main2 v-on:emit-event-main2-counter="sendToBottom"/>
<Bottom :cntr="pcounter"/>
....
</template>

data:{
pcounter:0
},
methods:{
sendToBottom(c){
this.pcounter=c
}
}

Bottom应该具有名为cntr的属性

props:["cntr"]

底部.vue

<template>
<div  class="Bottom" >
bottom text and cntr ({{cntr}})
</div>
</template>
<script>
export default {
props:["cntr"],
data: () => {
return {
}
},
}
</script>

如果您想使用根事件,您需要用this.$root.$emit()发出事件,并监听根上的事件,如下所示:this.$root.$on()

您应该在脚本部分直接使用它。监听根事件,例如在created()钩子中,然后在beforeDestroy()钩子中用$off禁用它。


但是,我不鼓励您使用$root事件。通常最好是像@BoussadjraBrahim在他的回答中提出的那样在组件之间进行通信。

如果您有一个更复杂的应用程序,那么查看Vuex并将完整状态存储在Vuex存储中是有意义的。通过这样做,您可以观察组件中的全局应用程序状态,并在其更改时做出反应。在这种情况下,您将使用Vuex存储,而不是根EventBus。

最新更新