需要下载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>