浏览器不同tab页通讯问题
vue2项目 后台管理系统需求就是点击某个链接之后,浏览器新开了一个tab页签,
然后在新开的页签操作数据之后,旧的页签就造成数据的滞后。
解决方式:浏览器通讯 使用 BroadcastChannel 属于web自带api
缺点:只能是同源的浏览器,谷歌与edge无法通讯 ,同一个浏览器的无痕与非无痕无法通讯
上代码
创建windowMsg.js
1 // 创建 BroadcastChannel 实例
2 export const windowChannel = new BroadcastChannel('windowChannel');
3
4 // 向其他客户端发送消息
5 export const windowChannelSend = (obj) => {
6 windowChannel.postMessage(obj);
7 }然后挂载到 vue 上面 main.js
1 // 浏览器通讯
2 import { windowChannel,windowChannelSend} from "@/config/windowMsg";
3 Vue.prototype.$windowChannel = windowChannel;
4 Vue.prototype.$windowChannelSend = windowChannelSend;数据传输,数据源 a.vue
1 methods: {
2 sendWindowMsg(){
3 this.$windowChannelSend({name: '李逍遥',age: 20})
4 },
5 }数据接收,b.vue
1mounted() {
2 let that = this
3 this.$windowChannel.addEventListener('message', event => {
4 that.getMsg(event.data)
5 });
6 },
8 methods: {
9 getMsg(obj) {
10 console.log(obj, '接收到消息');13 },
14 }数据传输之后,需要在合适地方将这个通讯关闭,看自己需要
1this.$windowChannel.close();
以上代码可以实现基础功能
原本想将监听与关闭同时封装到 windowMsg.js 但是出现了数据无法暴漏出去的问题,有没有大佬能帮我看一下怎么解决
第三行可以输出接收到数据,但是这个数据无法返回到B.vue 界面,在b界面输出 this.$windowChannelGet 是null
1 // 监听消息
2 export const windowChannelGet = windowChannel.addEventListener('message', event => {
3 console.log('Received message:', event.data);
4 return event.data
5 });
来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除
页:
[1]