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>



在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxslxskxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值