同源頁面
A頁面打開B頁面,B頁面的業(yè)務(wù)進(jìn)行完成后,B頁面需要觸發(fā)A頁面的某刷新方法
廣播模式,頁面將消息通知給一個(gè)中轉(zhuǎn),中轉(zhuǎn)再通知給各個(gè)頁面。中轉(zhuǎn)可以是一個(gè) BroadCast Channel 實(shí)例、一個(gè) Service Worker 或是 LocalStorage。
BrocastChannel
BrocastChannel可以實(shí)現(xiàn)同源下瀏覽器不同窗口,tab頁,frame或frame下的瀏覽器上下文之間的通信。
// a頁面
var bc = new BroadcastChannel('qwer')
bc.postMessage('發(fā)送數(shù)據(jù)')
// b頁面
var bc = new BroadcastChannel('qwer')
bc.onmessage = function(e) {
console.log(e)
}
/** 消息發(fā)送后,所有連接到該頻道的 BrocastChannel對象上都會(huì)觸發(fā) meaasge事件,
該事件沒有默認(rèn)行為,可以使用`onmessage`事件處理程序來定義一個(gè)函數(shù)處理消息
**/
LocalStorage
LocalStorage是前端常用的本地存儲(chǔ),當(dāng)LocalStorage變化是,會(huì)觸發(fā)storage事件,發(fā)送消息時(shí),將消息寫入LocalStorage中,然后在各個(gè)頁面中,通過監(jiān)聽storage事件即可收到通知。
// a頁面
window.addEventListener('storage', function(e) {
console.log(e)
})
// b頁面
localStorage.setItem('qwer', 10000)
1、A頁面的mounted里監(jiān)聽
let CHANNEL_CODE = 'refreshTable'
this.listenChannel = new BroadcastChannel(CHANNEL_CODE);
this.listenChannel.onmessage = (res) => {
// console.log(res);
if (res.data.success) {
that.bs.queryTableList();
}
};
// 注意在A頁面里這里要銷毀
beforeDestory(){
this.listenChannel.close();
}
2、B頁面觸發(fā)
let CHANNEL_CODE = 'refreshTable'
let listenChannel = new BroadcastChannel(CHANNEL_CODE);
listenChannel.postMessage({
type: 'refreshTable',
success: 'true' + Math.random()
});
console.log("觸發(fā)刷新數(shù)據(jù)" )
listenChannel.close();
Vuex
如果是vue項(xiàng)目
還可以考慮將監(jiān)測數(shù)據(jù)存入到store里,在A頁面的computed拿到檢測數(shù)據(jù),然后watch數(shù)據(jù)的變化;
或者在瀏覽器緩存存儲(chǔ)檢測數(shù)據(jù),在A頁面定時(shí)器獲取檢測數(shù)據(jù)來判斷變化
通過事件的發(fā)布訂閱模式
代碼實(shí)現(xiàn)
utils/msgCenter.js
class msgCenter {
constructor() {
}
msgObj = new Object();
on = (msgName, func) => {
this.msgObj[msgName] = func;
}
one = (msgName, func) => {
this.msgObj[msgName] = func;
}
emit = (msgName, data) => {
if (!Object.prototype.hasOwnProperty.call(this.msgObj, msgName)) return;
this.msgObj[msgName](data);
}
off = (msgName) => {
if (!Object.prototype.hasOwnProperty.call(this.msgObj, msgName)) return;
delete this.msgObj[msgName];
}
}
export default new msgCenter()
使用:
發(fā)布事件
import $SLMC from "@/utils/msgCenter";
$SLMC.emit("refreshTable", data);
訂閱事件
import $SLMC from "@/utils/msgCenter";
$SLMC.on("refreshTable", this.refreshTable);