Is there any way to ‘watch’ for localstorage in Vuejs?

localStorage is not reactive but I needed to “watch” it because my app uses localstorage and didn’t want to re-write everything so here’s what I did using CustomEvent.

I would dispatch a CustomEvent whenever you add something to storage

localStorage.setItem('foo-key', 'data to store')

window.dispatchEvent(new CustomEvent('foo-key-localstorage-changed', {
  detail: {
    storage: localStorage.getItem('foo-key')
  }
}));

Then where ever you need to watch it do:

mounted() {
  window.addEventListener('foo-key-localstorage-changed', (event) => {
    this.data = event.detail.storage;
  });
},
data() {
  return {
    data: null,
  }
}

Leave a Comment