token - {{token}}

Script: comp...">

Is there a way to "look" at localstorage in Vuejs?

I am trying to observe localstorage:

Template:

<p>token - {{token}}</p> 

Script:

 computed: { token() { return localStorage.getItem('token'); } } 

But that does not change when the token changes. Only after refreshing the page.

Is there a way to solve this problem without using Vuex or state management?

+12
source share
4 answers

Sure! Best practice, in my opinion, is to use getter / setter to wrap a local file.

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 JSFiddle .

+14
source

If you want to avoid patterns (getter / setter-syntax syntax), use vue-persistent-state to get reactive constant state.

For instance:

 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>' }) 

token is now available as data in all Vue components and instances. Any changes to this.token will be stored in localStorage, and you can use this.token as in the vanilla Vue application.

The plugin is mainly watcher and localStorage.set . You can read the code here . it

  1. adds a initialState to make initialState available in all Vue instances, and
  2. monitors changes and stores them.

Disclaimer : I am the author of vue-persistent-state .

+5
source

The VueJs website has a page about this. https://vuejs.org/v2/cookbook/client-side-storage.html

They provide an example. Given this HTML template

 <template> <div id="app"> My name is <input v-model="name"> </div> <template> 

They provide this use of the method, mounted throughout the life cycle, and the observer.

 const app = new Vue({ el: '#app', data: { name: '' }, mounted() { if (localStorage.name) { this.name = localStorage.name; } }, watch: { name(newName) { localStorage.name = newName; } } }); 

mounted method ensures that name set from local storage, if it already exists, and an observer allows your component to respond whenever the name in local storage changes. This works well when data in local storage is added or changed, but Vue will not respond if someone erases their local storage manually.

+3
source

You can do this in two ways,

  1. using vue-ls and then adding a listener to the storage keys, with

      Vue.ls.on('token', callback) 

    or

      this.$ls.on('token', callback) 
  2. using the DOM repository event handler:

      document.addEventListener('storage', storageListenerMethod); 
0
source

Source: https://habr.com/ru/post/1265820/


All Articles