使用 localStorage 實現多頁面通訊

需求背景

兩個頁面 A、B,B 頁面關閉時,通知 A 頁面請求接口刷新列表頁

實現

使用 storage 事件實現頁面通訊,約定好通訊的 key,這裏咱們假定 key 爲 refresh_listbash

A 頁面 監聽 storage 事件this

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 值,關閉頁面spa

methods: {
  close() {
    localStorage.setItem('refresh_list', new Date().getTime());
    try {
        window.close();
      } catch (e) {
        console.log(e);
    }
  },
},
相關文章
相關標籤/搜索