使用Vue.js跨浏览器选项卡的反应性localStorage对象 [英] Reactive localStorage object across browser tabs using Vue.js

查看:54
本文介绍了使用Vue.js跨浏览器选项卡的反应性localStorage对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使localStorage对象具有反应性,以便如果它更新,它也将在使用相同对象的其他选项卡中更新.我正在使用 Vue.js 并尝试创建一个返回 localStorage 对象的计算属性,但这不起作用.如何使对象具有反应性,并且还可以在其他浏览器选项卡中对其进行更新?

I'm trying to make a localStorage object reactive, so that if it updates, it will also update in other tabs using that same object. I'm using Vue.js and have tried to create a computed property that returns the localStorage object, but this doesn't work. How can I make the object reactive and make it update in other browser tabs also?

computed: {
  localStorageObject() {
    return JSON.parse(localStorage.getItem('object'));
  }
}

推荐答案

@Matthias是答案的开始,但不会对其他选项卡中的更改做出反应.为此,您可以处理 StorageEvent .这是一个粗略的草图,您可以根据需要进行增强.

@Matthias has the start of an answer, but it won't react to changes in other tabs. To do that, you can handle the StorageEvent. Here's a rough sketch that you could enhance as desired.

const app = new Vue({
  el: '#app',
  data: {
    name: ''
  },
  methods: {
    onStorageUpdate(event) {
      if (event.key === "name") {
        this.name = event.newValue;
      }
    }
  },
  mounted() {
    if (localStorage.name) {
      this.name = localStorage.name;
    }
    window.addEventListener("storage", this.onStorageUpdate);
  },
  beforeDestroy() {
    window.removeEventListener("storage", this.onStorageUpdate);
  },
  watch: {
    name(newName) {
      localStorage.name = newName;
    }
  }
});

这篇关于使用Vue.js跨浏览器选项卡的反应性localStorage对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆