bus主要实现组件之间的通信,较于组件之间的子传父,父再传另一子组件方便了很多
首先创建一个bus.js
import Vue from 'vue'
const bus = new Vue()
export default bus
父页面
<template>
<div class="demo-wrapper">
<comA />
<comB />
</div>
</template>
<script>
import comA from "./componentA";
import comB from "./componentB";
export default {
components: {
comA,
comB,
},
};
</script>
组件A
<template>
<div>
<button @click="handleClick">点我修改B的值</button>
</div>
</template>
<script>
import bus from "@/utils/bus";
export default {
data() {
return {};
},
methods: {
handleClick(){
bus.$emit('busChange','A传递给B的值')
},
},
};
</script>
<style>
</style>
组件B
<template>
<div></div>
</template>
<script>
import bus from "@/utils/bus";
export default {
data() {
return {};
},
mounted() {
bus.$on("busChange", (e) => {
console.log(e);
});
},
methods: {},
};
</script>
<style>
</style>
以上简单的功能就实现了
接下来进行进一步的封装,能够更方便的去使用它
vue-bus.js
const install = function(Vue) {
const Bus = new Vue({
methods: {
emit (event, ...args) {
this.$emit(event, ...args);
},
on (event, callback) {
this.$on(event, callback);
},
off (event, callback) {
this.$off(event, callback);
},
}
})
Vue.prototype.$bus = Bus;
}
export default install;
在main.js中引用:
import VueBus from './vue-bus';
Vue.use(VueBus);
接在来就可以在项目中使用了
this.$bus.on('busChange',(e)=>{
});
this.$bus.emit('busChange','要传的值,也可以是方法')