Vue全局事件总线详解
简介:全局事件总线是一种组件间通信的方式,适用于任意组件间通信。
可以调用 $on 、 $off 和 $emit 方法,因为这三个方法在Vue原型对象上,所以我们的全局事件总线就要放在Vue的原型对象(vue.prototype)上,以确保每个组件都能访问得到。
实现:
main.js:
new Vue({
el: '#app',
router,
store,
beforeCreate() {
Vue.prototype.$bus = this // 配置全局事件总线
},
render: h => h(App)
})
子组件 Student.vue
<template>
<div class="student">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张三',
age: '20'
}
},
methods: {
sendStudentName() {
this.$bus.$emit('hello', this.name)
}
}
}
</script>
子组件 School.vue
<template>
<div class="school">
<h2>学校:{{ name }}</h2>
<h2>地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: '家里蹲大学',
address: 'home'
}
},
mounted() {
this.$bus.$on('hello', (data) => {
console.log('我是School组件 收到了数据', data)
})
},
beforeDestroy() {
this.$bus.$off('hello') // 销毁阶段,$off解绑当前组件所用到的事件
}
}
</script>
父页面
<template>
<div>
<Student />
<School />
</div>
</template>
<script>
import Student from './component/Student'
import School from './component/School'
export default {
components: {
Student,
School
}
}
</script>