2

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

2 Answers 2

20

@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;
    }
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Maybe add a focus event listener on document/window which does the same as the mounted part in the example above? EDIT: nevermind, just realized there is an answer already

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.