一、eventBus(全局事件总线)
使用介绍
EventBus又称为事件总线,可以使用它来进行组件之间通信。其实和vuex还是有些类似的,相当于所有组件共用一个事件中心,这个事件中心用来管理事件,当我们需要用到的时候就向事件中心发送或者接受事件。通过共享一个vue实例,使用该实例的$on以及$emit实现数据传递。
使用场景
- 隔代组件通信(父传子,子传父)
- 兄弟组件通信
使用方法
1、接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){
demo(data){......}
}
......
mounted() {
this.$bus.$on('xxxx',this.demo)
}
2、提供数据:this.$bus.$emit('xxxx',数据)
3、最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
代码演示
main.js
// 引入Vue
import Vue from 'vue'
// 引入App
import App from './App.vue'
// 引入Vue-router
import router from './router'
// 引入Vuex
import store from './store'
// 关闭Vue的生产提示
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
}
}).$mount('#app')
在a组件(接收数据的)的生命周期钩子中添加事件到事件总线上 回调留在自身
<template>
<div>
<h1>我是A</h1>
<hr>
<h2>{{name}}</h2>
</div>
</template>
<script>
export default {
data() {
return {
data:"兄弟传参",
name:""
}
},
mounted() {
this.$bus.$on("hello", (e) => {
console.log(e)
console.log("我是MyChild组件,收到了数据", e);
this.name=e
});
},
beforeDestroy() {
this.$bus.$off("hello");
},
};
</script>
<style lang="scss" scoped>
</style>
然后在b组件(提供数据的)内触发事件总线上对应的事件(通过事件触发)
<template>
<div>
<h1>{{ name }}</h1>
<button @click="sendStudentName">提交</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "我是B",
};
},
methods: {
sendStudentName() {
this.$bus.$emit("hello", this.name);
},
},
};
</script>
<style lang="scss" scoped>
</style>
父组件:
<template>
<div>
<h1>我是父组件</h1>
<my-brother></my-brother>
<my-child></my-child>
</div>
</template>
<script>
import MyBrother from "../components/MyBrother.vue";
import MyChild from "../components/MyChild.vue";
export default {
components: { MyBrother, MyChild },
};
</script>
<style lang="scss" scoped>
</style>