vue2.X下窗口和窗口之间通信

今天工作中遇到一个问题,vue2.x架构下,在A页面中window.open一个新窗口B,然后新窗口然后在B窗口里触发A窗口事件。

想了下决定用portMessage来实现

下面上代码

A窗口

methods:{
 AbuttonEvent(){
      window.open(href, "_blank");
  }
}
复制代码

在A页面里,通过按钮事件AbuttonEvent触发,来新打开一个窗口。

B窗口

methods:{
 BbuttonEvent(){
    let href = window.location.origin;
    window.opener.postMessage("message", href);
  }
}
复制代码

在B页面里,通过一个按钮事件BbuttonEvent触发,来向A窗口发送消息

在项目的main.js里加入代码

Vue.prototype.$bus = new Vue();
window.addEventListener("message", (e) => {
 console.log(e, "sssssssssssssssssssssss");
  Vue.prototype.$bus.$emit('getTable')
});
复制代码

剩下来的就是在A窗口里接收$bus,然后触发A窗口的事件。

以上是我排除坑的代码,下节我再补充我遇到的坑以及解决办法,有更好方案的大佬欢迎留言。下班。。。。。。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享