vue通过BroadcastChannel实现不同标签页直接传递消息

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);
相关推荐
hugo_im几秒前
GrapesJS 完全指南:从零构建你的可视化拖拽编辑器
前端·javascript·前端框架
用户90470668357几秒前
nuxt 路由一篇讲清楚
前端
盘子素几秒前
前端实现跳转子系统,但限制只能跳转一次
前端·javascript
Anita_Sun1 分钟前
Lodash 源码解读与原理分析 - Lodash 前世今生:设计原则与演进脉络
前端
爱吃羊的老虎5 分钟前
Streamlit:快速创建应用界面,无需了解 Web 开发
前端·python
满栀5857 分钟前
三级联动下拉框
开发语言·前端·jquery
杨超越luckly14 分钟前
HTML应用指南:利用GET请求获取网易云热歌榜
前端·python·html·数据可视化·网易云热榜
前端_yu小白15 分钟前
React实现Vue的watch和computed
前端·vue.js·react.js·watch·computed·hooks
多看书少吃饭17 分钟前
OnlyOffice 编辑器的实现及使用
前端·vue.js·编辑器
float_六七20 分钟前
JS比较运算符:从坑点速记到实战口诀
开发语言·javascript·ecmascript