一、建立bus.js
import Vue from 'vue';
// 使用 Event Bus
const bus = new Vue();
export default bus;
二、兄组件
通过$emit 向兄弟组件传参
<script>
import bus from "./bus";
export default {
name: "Header",
data(){
collapse:true
},
methods: {
// 侧边栏折叠
toggleCollapse() {
this.collapse = !this.collapse;
bus.$emit("collapse", this.collapse);
},
}
}
</script>
三、弟组件
通过$on 获取兄弟组件传递来的参数
<script>
import bus from "./bus";
export default {
name: "Header",
data(){
collapse:false
},
created(){
bus.$on("collapse", msg => {
this.collapse = msg;
});
}
}
</script>
bus.js 用途
1 组件间的通讯,传承 (组件必须引入bus.js);
2 结合route路由对象,keep-alive 使用,开启多标签页数据缓存方案;






网友评论