使用 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); } }, },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM