bus

作者: SecondRocker | 来源:发表于2019-07-09 20:39 被阅读0次

    当多个组件之间进行通讯时,再使用$children 、$ref就会很麻烦,这时候使用bus会降低复杂度
    bus.js

    const install = function(Vue){
      let 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 bus from './components/bus'
    
    Vue.use(bus)
    
    //b组件中发送消息
    this.$bus.emit('message',data)
    
    // 可以在 a组件中 中 接收消息
    this.$bus.off('message',(data) => {
          console.log('off event')
    });
    
    //停止消息
    this.$bus.off('message',() => {
        console.log('off message')
    })
    

    相关文章

      网友评论

          本文标题:bus

          本文链接:https://www.haomeiwen.com/subject/jrawxctx.html