vue中手写一个发布订阅模式实现组件的通信

utils/bus.js



// 发布订阅者模式也称为观察者模式
// 订阅发布模式在开发中用到的设计模式中还是比较常见的
class Observer {
  constructor() {
    this.message = {}; //消息队列
  }
  $on(type,callback) {
     // 判断是否有订阅类型
     console.log("type===",type)
    if(!this.message[type]) {
      console.log(this.message[type])
      // 初始化没有这个属性,我就添加一个
      this.message[type] = [callback]
    } else {
      this.message[type].push(callback)
    }
  }
  isValue(arg) {
    let flag = Object.prototype.toString.call(arg) == "[object Array]" || Object.prototype.toString.call(arg) == "[object Object]"
    if(flag) {
      if(arg instanceof Array) {
       return arg.length ? arg : null
      }
      return Object.keys(arg).length ? arg : null
    } else {
      return arg ? arg : null
    }
  }
  $emit(type,arg=null) {
    let args = this.isValue(arg)
    // 判断是否有订阅类型
    if(!this.message[type]) return
    this.message[type].forEach(callback => {
      callback(args)
    });
  }
  $off(type,callback) {
    // 判断是否有订阅类型
    if(!this.message[type]) return
    if(!callback) return
    // 如果有callback这个类型就删除掉
    this.message[type] = this.message[type].filter(item => item != callback)
  }
}
export default new Observer()



main.js引入bus全局注册

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import $bus from './utils/bus'

Vue.config.productionTip = false
Vue.prototype.$bus = $bus

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

app.vue组件

<template>
  <div id="app">
    1212
    <Cart></Cart>
    <button @click="handlerBus">bus事件</button>
  </div>
</template>

<script>
import Cart from './components/Cart.vue'
  export default {
    components:{
      Cart
    },
    data() {
      return {
        count: 0
      }
    },
    methods: {
      handlerBus() {
        this.count++
        this.$bus.$emit("sendTitle",this.count)
      }
    },
  }
</script>

cart.vue

<template>
  <div class="hello">
    {{count}}
  </div>
</template>

<script>
export default {
  name: 'Cart',
  data() {
    return {
      count: 0
    }
  },
  mounted() {
    this.$bus.$on("sendTitle",e=>{
      console.log(e)
      this.count = e
    })
  },
  beforeDestroy() {
        this.$bus.$off("sendTitle",()=>{})
  }
}
</script>



在这里插入图片描述


版权声明:本文为lxs19930928原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。