跨页面标签页通讯 - BroadcastChannel

2024-04-17  本文已影响0人  Coldhands
const channel = new BroadcastChannel("sync-refresh");

/**
 * @param { "refresh" } type
 * @param { any } msg
 */
export function sendMsg(type: string, msg: any = "") {
  channel.postMessage({
    type,
    msg
  });
}

export function listenMsg(callback: any) {
  const handler = (e: any) => {
    callback && callback(e.data);
  };
  channel.addEventListener("message", handler);
  return () => {
    channel.removeEventListener("message", handler);
  };
}

// 使用方法
// listenMsg((info) => {
//   info.type
//   info.msg
// })

// 监听登录刷新页面
const unListen = listenMsg((info: any) => {
  // todo
});

// 取消监听
onUnmounted(unListen);
上一篇 下一篇

猜你喜欢

热点阅读