需要下载npm I pubsub-js
在Student.vue中发送数据
<template>
<div class="demo">
<h2 class="title">学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">将学生名给School组件</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'Student',
data(){
return{
name:'李四',
sex:"男"
}
},
methods:{
sendStudentName(){
pubsub.publish('hello',this.name)
}
}
}
</script>
<style scoped>
.demo{
background-color: orange;
}
</style>
在School.vue中接收数据
<template>
<div class="demo">
<h2 class="title">学校名称:{{name }}</h2>
<h2>学校地址:{{addr}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'School',
data(){
return{
name:'尚硅谷atguigu',
addr:'北京'
}
},
methods:{
demo(msgName,data){
console.log('有人发布了hello消息,hello消息回调执行了',msgName,data)
}
},
mounted(){
this.pubId= pubsub.subscribe('hello',this.demo)
},
beforeDestroy(){
pubsub.unsubscribe(this.pubId)
}
}
</script>
<style scoped>
.demo{
background: skyblue;
}
</style>


![Android ChatOn-v1.66.536-598-[构建于ChatGPT和GPT-4o之上]](https://i-blog.csdnimg.cn/direct/5b0b070c70864b2fb25f348dad9ae8d1.png)







![[自动驾驶-传感器融合] 多激光雷达的外参标定](https://i-blog.csdnimg.cn/direct/d246557947b14893b37309775eb04cdc.png)





![[AI]从零开始的so-vits-svc歌声推理及混音教程](https://i-blog.csdnimg.cn/direct/9fd8ed2a6fca42ee860678ad53c302df.png)
