1.概述
通过创建一个新的vm对象,专门统一注册事件,供所有组件共同操作,达到所有组件随意隔代传值的效果
也就是:各个组件内部要传输的数据或者要执行的命令信息,靠bus来通信。
2. 代码实现
2.1 全局引入
全局引入的话,就直接在main.js里面引入即可:
// 创建 bus总线
Vue.prototype.eventBus = new Vue();
2.2 按需引入
创建一个js文件
// bus.js
import Vue from 'vue';
const bus = new Vue();
export default bus
3.组件中使用
3.1 抛出数据给其他组件调用
全局引入的调用
// 提交这一列的数据
this.eventBus.$emit("equipment16CList", this.equipment16CList);
按需引入的调用,需要先导入Bus的js
// 提交这一列的数据
bus.$emit("equipment16CList", this.equipment16CList);
3.2 组件获取其他组件抛出的数据
// 组件加载完
mounted() {
// 拿到前一列的数据
this.eventBus.$on("equipment16CList", (value) => {
this.beforeLineEquipment16CList = value;
// 设置设备宽高
this.setEquipmentInfor();
// 绘制设备
this.drawEquipLine2();
// 提交这一列的数据
this.eventBus.$emit("equipment17HTList", this.equipment17HTList);
});
},
3.3 组件销毁时销毁监听(非常重要!!!)
// 生命周期 销毁
destroyed() {
this.eventBus.$off("equipment16CList");
},
4.注意点
1.在父组件引入子组件的时候,需要注意引入的顺序,把需要监听获取其他子组件的数据子组件放在前面先渲染出来。
equipLine02 需要拿取equipLine01 里面抛出的数据,所以要equipLine02 放在前面
<equipLine02 @equipClick="chileEquipClick"></equipLine02>
<equipLine01 @equipClick="chileEquipClick"></equipLine01>
- 注意一定要销毁监听,不然浏览器的内存会越来越大,直接导致浏览器崩溃