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?
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 .
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
- adds a
initialStateto makeinitialStateavailable in all Vue instances, and - monitors changes and stores them.
Disclaimer : I am the author of vue-persistent-state .
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.