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{