23_全局事件总线
任意组件间通信

main.js
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus=this //安装全局事件总线
}
}).$mount('#app')
School.vue
<template>
<div class="demo">
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址: {{address}}</h2>
</div>
</template>
<script>
export default{
name:'School',
data() {
return {
schoolName: "尚硅谷",
address: "北京",
};
},
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是school组件,收到了数据',data);
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
};
</script>
<style>
.demo{
background-color: orange;
}
</style>
student.vue
<template>
<div>
<h2>学生名称:{{ name }}</h2>
<h2>学生年龄: {{ age }}</h2>
<button @click="senStudentName">把学生名给school组件</button>
</div>
</template>
<script>
export default {
name: "Student", //变量 一般和文件名一样
data() {
return {
name: "张三",
age: 18,
};
},
mounted(){
// console.log(this.x);
},
methods:{
senStudentName(){
this.$bus.$emit('hello',666)
}
}
};
</script>
<style></style>
消息订阅与发布

School.vue 订阅消息
<template>
<div class="demo">
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址: {{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default{
name:'School',
data() {
return {
schoolName: "尚硅谷",
address: "北京",
};
},
mounted(){
// this.$bus.$on('hello',(data)=>{
// console.log('我是school组件,收到了数据',data);
// })
this.pubId= pubsub.subscribe('hello',function(msgName,data){
console.log("有人发布了hello消息",msgName,data);
})
},
beforeDestroy(){
// this.$bus.$off('hello')
pubsub.unsubscribe(this.pubId)
}
};
</script>
<style>
.demo{
background-color: orange;
}
</style>
Student.vue 发布消息
<template>
<div>
<h2>学生名称:{{ name }}</h2>
<h2>学生年龄: {{ age }}</h2>
<button @click="senStudentName">把学生名给school组件</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: "Student", //变量 一般和文件名一样
data() {
return {
name: "张三",
age: 18,
};
},
mounted(){
},
methods:{
senStudentName(){
// console.log( this.$bus);
pubsub.publish('hello',666)
}
}
};
</script>
<style></style>
$nextTick

this.$nextTick(function{
this.$refs.inputTitle.focus()
})
本文介绍了在 Vue.js 应用中如何使用全局事件总线和 PubSub-js 库实现组件间的通信。通过在 main.js 中创建全局事件总线,并在 School 和 Student 组件中分别订阅和发布事件,展示了消息订阅与发布的流程。同时提到了 $nextTick 方法用于在 DOM 更新后执行特定操作,确保聚焦操作的正确执行。
1726

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



