- 一种组件间通信的方式,适用于任意组件间通信
- 安装全局事件总线:在main.js文件中添加生命周期钩子
beforeCreate() { Vue.prototype.$bus = this }
,$bus就是当前应用的vm - 使用事件总线:
- 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
methods() {
demo(data) {......}
}
......
mounted() {
this.$bus.$on('demo', this.demo)
}
- 提供数据:
this.$bus.$emit('demo', 数据)
- 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
示例完整代码
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
el: '#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this
}
})
App.vue
<template>
<div class="app">
<h1>{{msg}}</h1>
<School />
<Student />
</div>
</template>
<script>
import Student from './components/Student'
import School from './components/School'
export default {
name: 'App',
components: {
School,
Student
},
data() {
return {
msg: '你好啊!',
}
}
}
</script>
<style scoped>
.app {
background-color: gray;
padding: 5px;
}
</style>
组件
School.vue
<template>
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: '尚硅谷',
address: '北京',
}
},
mounted() {
this.$bus.$on('hello', (data) => {
console.log('我是School组件,收到了数据', data)
})
},
beforeDestroy() {
this.$bus.$off('hello')
},
}
</script>
<style scoped>
.school {
background-color: skyblue;
padding: 5px;
}
</style>
Student.vue
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男',
}
},
mounted() {
},
methods: {
sendStudentName() {
this.$bus.$emit('hello', this.name)
}
},
}
</script>
<style lang="less" scoped>
.student {
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>