Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to 'watch' for localstorage in Vuejs?

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?

like image 584
artem0071 Avatar asked Mar 23 '17 11:03

artem0071


People also ask

How do I get localStorage value in VueJs?

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.

How do I use session storage in VUE JS?

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.

How do I change local storage value in Vue?

localStorage. setItem(USER_INFO, JSON. stringify(userData)); You can read, update and store again.


2 Answers

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.

like image 57
FitzFish Avatar answered Oct 09 '22 15:10

FitzFish


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,   } } 
like image 39
Salam Avatar answered Oct 09 '22 17:10

Salam