I have a section that shows a Login
button when there a user is not authenticated(as shown in localStorage), otherwise username
and a 'logout botton' will be shown.
The code works when I put the authenticated
inside the data
block. However, if I put it in the computed
field, it always shows login
#template
<router-link v-if="!authenticated" to="login">Log In</router-link>
<template v-else>
Logged in as {{username}}
<button @click="logout">Log out</button>
</template>
#script
data: function() {
return {
// get authenticated() { //this works
// return localStorage.getItem('authenticated');
// },
}
},
computed: function() {
return {
authenticated: function() { //this does not work
return localStorage.getItem('authenticated');
}
}
},
Vue isn't able to observe changes to local storage items, and so the authenticated
computed property will forever return the same value because Vue caches the values of computed properties.
In this scenario you would typically use a method:
methods: {
authenticated() {
return localStorage.getItem('authenticated')
}
}
although your getter would work too.