Vue3学习笔记-10
一、全局事件总线
1.全局事件总线:任意组件之间通信


二、全局事件总线的例子
实现同级组件之间的通信:
School.vue的代码:
<template>
<div class="root">
<!---->
<h2>学校的名称:{
{schoolName}}</h2>
<h2>学校的地址:{
{address}}</h2>
</div>
</template>
<script>
export default {
name:'School',
data() {
return {
name:'LYU',
address:'兰山区'
}
},
mounted(){
//console.log('hello',this.x)
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data)
})
},
beforeDestroy(){
this.$bus.$off('hello')
},
}
</script>
<style>
/*组件的样式*/
.root{
background-color: orangered;
}
</style>
Student.vue的代码:
<template>
<div class="root">
<!---->
<h2>学生的姓名:{
{name}}</h2>
<h2>学生的年龄:{
{age}}</h2>
<button @click="sendStudentName">把学生姓名给School组件</button>
</div>
</template>
<style>
/*组件的样式*/
.root{
background-color: orangered;
}
</style>
<script>
//组件交互相关的代码
export default{
name:'Student',
data(){
return {
name:'张三',
age:18
}
},
mounted(){
// console.log('Student',this.x)
},

这篇博客介绍了Vue3中的全局事件总线,用于组件间的通信。通过实例展示了如何订阅和发布消息,以及如何在同级组件间进行通信。文章还提到了使用第三方库如EventBus来实现更通用的消息传递。
最低0.47元/天 解锁文章
1173

被折叠的 条评论
为什么被折叠?



