Vue: How to use localStorage with vue?

Created on 16 Dec 2015  ·  3Comments  ·  Source: vuejs/vue

I posted on chat(twice), nobody answered, so i am hoping i can get some help here.

I have a mixin isLoggedIn() that return true if item is present in localStorage and false if it isn't.
My question is, how can i re-evaluate the state when i update or remove item form localStorage, because i have some elements shown only if isLoggedIn is true?

And is it right to use v-show="isLoggedIn()" or would you suggest something else, i don't know what is the best practice for this?

Thanks guys.

Most helpful comment

The catch here is that localStorage is not reactive, so you need something that is reactive to trigger the changes. Basically, you use an object to represent the login state, and when you login/logout, you'd modify localStorage and that object together (and initialize that object by reading from localStorage on app load).

See http://vuejs.org/guide/application.html#State_Management
and https://auth0.com/blog/2015/11/13/build-an-app-with-vuejs/ which does exactly what you are trying to do.

All 3 comments

The catch here is that localStorage is not reactive, so you need something that is reactive to trigger the changes. Basically, you use an object to represent the login state, and when you login/logout, you'd modify localStorage and that object together (and initialize that object by reading from localStorage on app load).

See http://vuejs.org/guide/application.html#State_Management
and https://auth0.com/blog/2015/11/13/build-an-app-with-vuejs/ which does exactly what you are trying to do.

@yyx990803 Thanks man, this article is exactly what i am trying to do.

Where's the best place to check local storage at app initialization to see if the user's already logged in from a previous session? In the tutorial referenced, they just have a line inside the startup file / main.js before Vue is initialised. I've done something similar. Is that recommended?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

julianxhokaxhiu picture julianxhokaxhiu  ·  3Comments

lmnsg picture lmnsg  ·  3Comments

paceband picture paceband  ·  3Comments

WolfgangFellger picture WolfgangFellger  ·  3Comments

bfis picture bfis  ·  3Comments