crossTagMsg.js
const channel = new BroadcastChannel('demo');
export function sendMsg(type, content){
channel.postMessage({
type,
content,
});
}
export function listenMsg(callback){
const handler = (e) => {
callback && callback(e.data);
}
channel.addEventListener('message', handler);
return() => {
channel.removeEventListener('message', handler);
};
}
A.vue发送消息页面
import {listenMsg} from '@/utils/crossTagMsg'
function update(){
sendMsg("更新", "dddd")
}
B.vue监听消息页面
import {listenMsg} from '@/utils/crossTagMsg'
//监听消息
const cancelListen = listenMsg((msgInfo) => {
console.log('监听到了更新', msgInfo)
})
//组件销毁时移除监听
onBeforeUnmount(cancelListen);