使用過vue的同窗大多數都知道on的使用。咱們僅僅知道使用,有時候是徹底不夠的。如今我就帶領你們寫一個簡單相似於vue空實例的中間件。html
非父子組件的通訊vue官網給出這樣的解決方案。 有時候,非父子關係的兩個組件之間也須要通訊。在簡單的場景下,可使用一個空的 Vue 實例做爲事件總線:vue
var bus = new Vue()
// 觸發組件 A 中的事件
bus.$emit('id-selected', 1)
// 在組件 B 建立的鉤子中監聽事件
bus.$on('id-selected', function (id) {
// ...
})
複製代碼
下面是一個很簡單的例子bash
//工具
var myBus = (function() {
var clienlist = {},
addlisten, trigger, remove;
/**
* 增長訂閱者
* @key {String} 類型
* @fn {Function} 回掉函數
* */
addlisten = function(key, fn) {
if(!clienlist[key]) {
clienlist[key] = [];
}
clienlist[key].push(fn);
};
/**
* 發佈消息
* */
trigger = function() {
var key = [].shift.call(arguments), //取出消息類型
fns = clienlist[key]; //取出該類型的對應的消息集合
if(!fns || fns.length === 0) {
return false;
}
for(var i = 0, fn; fn = fns[i++];) {
fn.apply(this, arguments);
}
};
/**
* 刪除訂閱
* @key {String} 類型
* @fn {Function} 回掉函數
* */
remove = function(key, fn) {
var fns = clienlist[key]; //取出該類型的對應的消息集合
if(!fns) { //若是對應的key沒有訂閱直接返回
return false;
}
if(!fn) { //若是沒有傳入具體的回掉,則表示須要取消全部訂閱
fns && (fns.length = 0);
} else {
for(var l = fns.length - 1; l >= 0; l--) { //遍歷回掉函數列表
if(fn === fns[l]) {
fns.splice(l, 1); //刪除訂閱者的回掉
}
}
}
};
return {
$on: addlisten,
$emit: trigger,
$off: remove
}
})();
//組件一
Vue.component('vv-count', {
props: ["count"],
template: '<div>\ <span>{{count}}</span><button @click="handelClick" type="button">計算</button>\ </div>',
methods: {
handelClick() {
console.log('vv-count總計:', this.count);
if(vue_bus){
//觸發發佈--使用vue
bus.$emit("vv_count", this.count,'這是使用vue的')
}else{
//觸發發佈--使用本身的
myBus.$emit("vv_count", this.count,'這是本身寫的')
}
}
}
});
//組件二
Vue.component('vv-count1', {
props: ["count"],
template: '<div>\ <span>{{count}}</span><button @click="handelClick" type="button">計算</button>\ </div>',
methods: {
handelClick() {
console.log('vv-count1總計:', this.count);
if(vue_bus){
//觸發發佈
bus.$emit("vv_count", this.count)
}else{
//觸發發佈
myBus.$emit("vv_count", this.count)
}
}
}
});
var vue_bus=true;// true:使用vue的事件總線,false:使用本身的事件總線
if(vue_bus){
//中間件
var bus = new Vue();
//使用vue的事件總線--訂閱
bus.$on("vv_count", function() {
console.log("使用bus發佈的參數==", arguments);
});
}else{
//使用本身的事件總線--訂閱
myBus.$on("vv_count", function() {
console.log("使用myBus發佈的參數==", arguments);
});
}
new Vue({
el: "#app"
});
複製代碼
上面代碼可使用vue_bus=true 或者false 相互切換進行看效果。如圖所示:app
vue中的發佈訂閱跟本身寫的發佈訂閱原理是相同的,但願你們可以get到知識。函數
打賞通道--我以爲不會有打賞。工具