我正在 Main2.vue
中发出一个名为 emit-event-main2-counter 的事件为什么Bottom.vue中的数据cntr无法更新?
App.vue
._take()
Main2.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>
Bottom.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>
答案 0 :(得分:3)
您可以将Main2
作为参数this.counter
向父级发送事件,并在父级中接收事件并将其通过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"]
Bottom.vue
<template>
<div class="Bottom" >
bottom text and cntr ({{cntr}})
</div>
</template>
<script>
export default {
props:["cntr"],
data: () => {
return {
}
},
}
</script>
答案 1 :(得分:2)
如果要使用根事件,则需要使用this.$root.$emit()
发出事件,并在根上监听事件,如下所示:this.$root.$on()
。
您应该直接在脚本部分中使用它。听根事件,例如created()
挂钩中,然后在beforeDestroy()
挂钩中使用$off
禁用它。
但是,我不鼓励您使用$root
事件。通常最好在answer中提出的@BoussadjraBrahim之类的组件之间进行通信。
如果您有一个更复杂的应用程序,则有必要查看Vuex并将完整状态存储在Vuex存储中。这样,您可以监视组件中的全局应用程序状态,并在其更改时做出反应。在这种情况下,您将使用Vuex存储而不是根EventBus。