vue--day--53----消息订阅实现组件通讯

1. 安装组件。npm i pubsub-js

2.main.js

/**
* 该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
// 引入App 组件 他是所有组件的父组件
import App from './App.vue'

//关闭vue 的生产提示
Vue.config.productionTip = false
// const Demo=Vue.extend({})
// const d=new Demo();
// Vue.prototype.x=d;
// 创建Vue 实例对象--vm
new Vue({
//将 app 组件放入到容器中
render: h => h(App),

// beforeCreate(){
// Vue.prototype.$bus=this // 安装全局事件总监
// }
}).$mount('#app')
3. Student.vue
<template>
<div class="student">
 
<h2>学生姓名{{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(){
console.log('999999')
//this.$bus.$emit('hello',6666666)
pubsub.publish('hello','你好呀')
 
}
}

 
 
 
 
 
}
</script>

<style scoped>
/* 组件的样式 */
.student{
background-color:cadetblue;
 
}

</style>


4. Student.vue
<template>
<!-- 组件的介绍 -->
<div class="school">

<h2>学校名称{{name}}</h2>
<h2>学校地址{{address}}</h2>
 

</div>
</template>



<script>

import pubsub from 'pubsub-js'
export default {
name:"School",
props:['receiveSchoolName'],
data() {
return {
name: "洛阳理工",
address: "洛阳"
};
},
methods:{
demo(msgName,data){
console.log('消息收到了',data)
}
},
mounted(){
//console.log('school',this);
// this.$bus.$on('hello',(data)=>{
// console.log('我是school组件,我收到了数据',data)
// })
//第一种写法 箭头函数
// this.pubid=pubsub.subscribe('hello',(msgName,data)=>{
// console.log('有人发布了hello笑死,hello消息的回调执行了',msgName,data,this)
// })

//第二种写法
this.pubid=pubsub.subscribe('hello',this.demo);
 


},
beforeDestroy(){
//this.$bus.$off('hello')
pubsub.ubsubscribe(this.pubid)

}
 
}

 
</script>


<style scoped>
/* 组件的样式 */
.school{
background-color:orange;
margin-top: 20px;
}

</style>
5. App.vue
<template>
<div class="app">

<h1>{{ msg }}</h1>
<Student></Student>
<School></School>
</div>
 
</template>

<script>
//样式的引入和这里有关系
import Student from './components/Student.vue';
import School from './components/School.vue';


export default {
name: 'App',
components: {
School,
Student,
},
data(){
return {
msg:'你好呀'
}
 
},

 
}
</script>

<style scoped>
.app{
background-color: brown;
}
</style>
 
6.消息发布的总结

 

 

 

posted @ 2023-08-04 00:36  雪落无痕1  阅读(7)  评论(0编辑  收藏  举报