How to watch for local storage changes in Vue.js?

Sometimes, we want to watch for local storage changes in Vue.js.

In this article, we’ll look at how to watch for local storage changes in Vue.js.

How to watch for local storage changes in Vue.js?

To watch for local storage changes in Vue.js, we can listen to the document‘s storage event.

For instance, we write

<script>
export default {
  methods: {
    storageListener() {
      //...
    },
  },
  mounted() {
    document.addEventListener("storage", this.storageListener);
  },
  beforeDestroy() {
    document.removeEventListener("storage", this.storageListener);
  },
};
</script>

to call document.addEventListener with 'storage' and the this.storageListener method to call this.storageListener when the local storage content changes in the mounted hook when the component is mounted.

Then in the beforeDestroy hook, we call removeEventListener to remove the this.storageListener as the storage event listener when the component unmounts.

Conclusion

To watch for local storage changes in Vue.js, we can listen to the document‘s storage event.