Vue.js中全局事件总线的理解—尚硅谷笔记
全局事件总线:它就相当于是一个行驶在一个道路上的公共汽车,Vue就是那个道路,路的起始位置是学生,路的终点是学校。
学生拿着作业(StudentForHomeWork())乘着汽车到学校。
1: 创建一个事件总线(汽车)
在main.js文件中:
new Vue({
render: h => h(App),
beforeCreate() {
// 1
Vue.prototype.$bus = this
}
}).$mount('#app')
2: 学生要去背书包
在Student.vue中定义一个事件叫背书包。
<template>
<div class="student">
<h1>{{msg}}</h1>
<!-- 父子组件传信息 -->
<button @click="StudentForHomeWork()">学生到学校</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return{
msg:'欢迎来到学生页面',
student:{
name:'zebra',
age: '18',
sex: '男'
}
}
},
methods:{
// 2 准备数据
StudentForHomeWork(){
this.$bus.$emit('busToSchool',this.student.name)
}
},
}
</script>
<style scoped>
.student{
background-color: pink;
}
</style>
3 学校收到作业
在School.vue文件中收到作业
<template>
<div class="school">
<h2> {{msg}}</h2>
</div>
</template>
<script>
export default {
name: 'School',
data(){
return{
msg:'欢迎来到学校页面',
}
},
mounted(){
this.$bus.$on('busToSchool',(data)=>{
console.log('学校收到了学生作业:',data)
})
},
methods:{}
}
</script>
<style scoped>
.school{
background-color: grey;
padding: 100px;
margin-top: 10px;
}
</style>
App.vue文件如下
<template>
<div id="app">
<h2>{{appData}},学生的姓名是:{{studentName}}</h2>
<Student/>
<!-- 自定义组件传信息 第一种 -->
<School/>
<!-- 自定义组件传信息 第二种 -->
<!-- <School ref="school" ></School>-->
</div>
</template>
<script>
import Student from './components/Student.vue'
import School from './components/School.vue'
export default {
name: 'App',
components: {
Student,
School
},
data(){
return{
appData: '你好啊',
studentName:''
}
},
beforeDestroy() {
this.$bus.$off('busToSchool')
console.log('销毁这个事件')
}
}
</script>
<style>
#app{
background-color: darkolivegreen;
padding: 100px;
}
</style>