Vue中使用localStorage实现同源跨标签页面的通信
Vue中使用localStorage实现同源跨标签页面的通信
·
实现原理
localStorage中支持监听storage变化时的事件,并且只有在不同标签页面,同源网页的时候才会触发,这里恰好解决的我们的需求:
window.addEventListener(‘storage’, callback);
示例
// 父页面(数据改变的位置设置)
localStorage.setItem("dialogOpen", this.dialogOpen);
// 子页面监听父页面的变化
mounted() {
const _that = this;
window.addEventListener("storage", function(e) {
console.log(e, "e");
if (e.key == "dialogOpen") {
_that.$nextTick(() => {
if (e.newValue == "true") {
_that.dialogOpen = true;
} else if (e.newValue == "false") {
_that.dialogOpen = false;
}
});
}
},
更多推荐

所有评论(0)