I'm attempting to watch for localstorage:
Template:
<p>token - {{token}}</p>
Script:
computed: { token() { return localStorage.getItem('token'); } }
But it doesn't change, when token
changes. Only after refreshing the page.
Is there a way to solve this without using Vuex or state management?
Inside the getCars method we just need a single line of code to pull the list from storage with vuejs localstorage. Now try to insert your first car and then click on get cars. You will be able to see the cars list. Refresh the browser and you will still be able to get the list.
We call set with the key and value of the data we want to save to save it. With session storage, different instances of the same app can store different data in their own session. The data can be set both per-origin and per-instance, which is per-window or per-tab.
localStorage. setItem(USER_INFO, JSON. stringify(userData)); You can read, update and store again.
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, } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With