使用 localStorage 实现多页面通信
需求背景
两个页面 A、B,B 页面关闭时,通知 A 页面请求接口刷新列表页
实现
使用 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);
}
},
},
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!