Is there any way to 'watch' for localstorage in Vuejs?
Sure thing! The best practice in my opinion is to use the getter / setter syntax to wrap the localstorage in.
Here is a working example:
HTML:
<div id="app"> {{token}} <button @click="token++"> + </button></div>
JS:
new Vue({ el: '#app', data: function() { return { get token() { return localStorage.getItem('token') || 0; }, set token(value) { localStorage.setItem('token', value); } }; }});
And a JSFiddle.
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, }}
Update: vue-persistent-state is no longer maintained. Fork or look else where if it doesn't fit your bill as is.
If you want to avoid boilerplate (getter/setter-syntax), use vue-persistent-state to get reactive persistent state.
For example:
import persistentState from 'vue-persistent-state'; const initialState = { token: '' // will get value from localStorage if found there};Vue.use(persistentState, initialState);new Vue({ template: '<p>token - {{token}}</p>'})
Now token
is available as data in all components and Vue instances. Any changes to this.token
will be stored in localStorage, and you can use this.token
as you would in a vanilla Vue app.
The plugin is basically watcher and localStorage.set
. You can read the code here. It
- adds a mixin to make
initialState
available in all Vue instances, and - watches for changes and stores them.
Disclaimer: I'm the author of vue-persistent-state.