使用 localStorage 实现多页面通信

需求背景

两个页面 A、B,B 页面关闭时,通知 A 页面请求接口刷新列表页

品牌vi设计公司http://www.maiqicn.com 办公资源网站大全https://www.wode007.com

实现

使用 storage 事件实现页面通信,约定好通信的 key,这里我们假定 key 为 refresh_list

A 页面 监听 storage 事件

mounted() {
  window.addEventListener('storage', this.otherWindowListener, false);
  this.$on('hook:beforeDestroy', () => {
    window.removeEventListener('storage', this.otherWindowListener);
  });
},
methods: {
  otherWindowListener(event) {
    if (event.key === 'refresh_list'){
      // do something
    };
  },
},

B 页面,当保存时,设置约定好的 localStorage key 值,关闭页面

methods: {
  close() {
    localStorage.setItem('refresh_list', new Date().getTime());
    try {
        window.close();
      } catch (e) {
        console.log(e);
    }
  },
},
原文地址:https://www.cnblogs.com/xiaonian8/p/13700127.html