Reactive localStorage object across browser tabs using Vue.js

為{幸葍}努か 提交于 2020-07-21 06:49:49

问题


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'));
  }
}

回答1:


@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;
    }
  }
});



回答2:


There is an example of how to achieve this on the Vue.js cookbook page: https://vuejs.org/v2/cookbook/client-side-storage.html

In the example, a name is stored in local Storage.

const app = new Vue({
  el: '#app',
  data: {
    name: ''
  },
  mounted() {
        if (localStorage.name) {
      this.name = localStorage.name;
    }
  },
  watch: {
    name(newName) {
      localStorage.name = newName;
    }
  }
});


来源:https://stackoverflow.com/questions/52780694/reactive-localstorage-object-across-browser-tabs-using-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!