任意两个组件传值可以Vuex,也可使用bus类
bus类:任意两个组件传值,可创建一个bus类负责事件派发、监听和回调管理
建立eventBus.js
src/assets/js/eventBus.js
const install = (Vue) => {
const Bus = new Vue({
methods: {
on (event, ...args) {
this.$on(event, ...args);
},
emit (event, callback) {
this.$emit(event, callback);
},
off (event, callback) {
this.$off(event, callback);
}
}
})
Vue.prototype.$bus = Bus;
}
export default install;
在main.js中引入eventBus
src/main.js
import Vue from 'vue'
import Bus from "@/assets/js/eventBus";
Vue.use(Bus);
组件中使用
src/xxx/xxx/xxx.vue
mounted() {
this.$bus.emit("sendFn", "传值到其它组件");
this.$bus.on("getFn", v=>"收到其它组件传值");
},
destroyed() {
this.$bus.off("getFn");
},