使用事件車(事件總線)實現組件通信

//創建一個用於通信的bus模塊
let bus = {
  install($){
    //在vue的原型上添加getBus和setBus
    $.prototype.getBus = this.get
    $.prototype.setBus = this.set
  },
  get(key){
    //如果實例上有bus對象,返回查詢結果,否則undefined
    if(this.bus){
      return this.bus[key]
    }else{
      return undefined
    }
  },
  set(key,value){
    //如果實例上沒有bus對象,創建一個,並設置屬性
    if(!this.bus){
      this.bus = {}
    }
    this.bus[key] = value
  }
}
Vue.use(bus);


//注:寫在vue中的main文件中即可.


//當我們在使用的時候。


created(){
	this.setBus('name','xiaoming');
	console.log(this.getBus('name'));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章