Vue 全局事件总线
发布于 2022年 05月 19日 01:28
全局事件总线又名:GlobalEventBus
安装全局事件总线
beforeCreate() {
Vue.prototype.$bus = this
}
使用事件总线
提供数据
this.$bus.$emit('xxx',数据)
接收数据
this.$bus.$on('xxx',数据)
注意:最好在 beforeDestroy 钩子中,用 $off 去解绑当前组件所用到的事件
beforeDestroy(){
this.$bus.$off('xxx')
}
实例
src 文件结构
|-- src
|-- App.vue
|-- main.js
|-- components
|-- MyStudent.vue
App.vue
<template>
<div class="app">
<h2>{{msg}}</h2>
<h2>学生姓名为:{{StudentName || '未收到'}}</h2>
<my-student/>
</div>
</template>
<script>
import MyStudent from "@/components/MyStudent";
export default {
name: 'App',
components: {MyStudent},
data() {
return {
msg: '你好',
StudentName: ''
}
},
// 接收数据
mounted() {
this.$bus.$on('hello', (data) => {
console.log('我是 App 收到学生姓名为:', data)
this.StudentName = data
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>
<style scoped>
.app {
background-color: #979696;
padding: 5px;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
// 安装全局事件总线
beforeCreate() {
Vue.prototype.$bus = this
}
}).$mount('#app')
MyStudent.vue
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给 App</button>
</div>
</template>
<script>
export default {
name: "MyStudent",
data(){
return {
name:'张三',
age:19
}
},
methods:{
// 提供数据
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
</script>
<style scoped>
.student{
background-color: #b2dece;
padding: 5px;
margin-top: 30px;
}
</style>