我在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.counter
的Main2
向父级发送事件,并且在父级中接收该事件并通过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。