vue组件之间的通信

安装 vue-bus

npm install vue-bus --save-dev

创建 vue-bus

/**
* 组件之间的通信
* @param Vue
*/
const install = (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

index.js

import VueBus from '@/common/vue-bus'
Vue.use(VueBus)

组件a 调用 组件b

# 组件 a
let num = Math.floor(Math.random() * 100 + 1);
this.$bus.$emit('getMenu', num);

# 组件 b
,created() {
    this.$bus.$on('getMenu', target => {
        // console.log(target);
        this.getMenus();
    });
}