I am currently in the process of creating a navigation bar that displays different buttons based on whether the user is logged in or not. To achieve this, I am utilizing Vuex and localStorage to manage the state.
My goal is to develop a dynamic menu using a list of objects (referred to as rightMenu
) which includes information about each button such as route, title, and a flag indicating whether the button should be displayed when the user is logged in.
After a user logs into the system, the
this.$store.state.auth.isUserLoggedIn
changes to true
. However, the template does not update accordingly, resulting in the buttons remaining in their initial state from when the user was not logged in. For instance, the 'sign out' button doesn't appear even after the this.$store.state.auth.isUserLoggedIn
updates. Only upon manually reloading the page with 'ctrl+F5', do the buttons display correctly.
In order to tackle this issue, I am considering forcing a page reload whenever a user logs in or out, although I realize this may not be the best solution.
Is there anyone who could offer assistance?
Below is the code snippet that I am currently working with:
Menu.vue > template
<div>
<v-toolbar color='grey darken-3' dark>
<v-toolbar-title>Site</v-toolbar-title>
...
<v-toolbar-items class='hidden-sm-and-down'>
<v-btn v-for='item in rightMenu' :key='item.title'
:to='item.to' v-if='item.showButton' flat>
{{ item.title }}
</v-btn>
</v-toolbar-items>
</v-toolbar>
<router-view/>
</div>
Menu.vue > script
export default {
data () {
return {
rightMenu: [
{ to: '/sign_in', title: 'sign in'
showButton: !this.$store.state.auth.isUserLoggedIn },
{ to: '/sign_up', title: 'sign up'
showButton: !this.$store.state.auth.isUserLoggedIn },
{ to: '/sign_out', title: 'sign out'
showButton: this.$store.state.auth.isUserLoggedIn }
]
}
},
...
}
store.js
const store = new Vuex.Store({
state: {
auth: {
token: '',
isUserLoggedIn: false
}
},
mutations: {
setAuthToken (state, token) {
state.auth.token = token
state.auth.isUserLoggedIn = !!token
localStorage.setItem('store', JSON.stringify(state))
},
cleanAuth (state) {
state.auth = {
token: '',
isUserLoggedIn: false
}
localStorage.setItem('store', JSON.stringify(state))
}
}
...
})
EDIT 1:
By directly referencing
this.$store.state.auth.isUserLoggedIn
in my code, the button visibility works as expected. An example is provided below:
Menu.vue > template
<v-toolbar-items class='hidden-sm-and-down'>
<v-btn v-if='this.$store.state.auth.isUserLoggedIn' flat>
Test {{ this.$store.state.auth.isUserLoggedIn }}
</v-btn>
</v-toolbar-items>
This leads me to believe that the issue lies in the binding between showButton
and
this.$store.state.auth.isUserLoggedIn
.