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()
})