Kris D. J.
Kris D. J.

Reputation: 72

Reactive localStorage object across browser tabs using Vue.js

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

Upvotes: 2

Views: 6127

Answers (2)

Matthias S
Matthias S

Reputation: 3553

There is an example of how to achieve this on the Vue.js cookbook page: https://v2.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;
    }
  }
});

Upvotes: 1

Stephen Thomas
Stephen Thomas

Reputation: 14053

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

Upvotes: 20

Related Questions