I am trying to "re-render" my navbar after the user logs in from the login page. I have certain nav links that will show depending on whether or not the user is logged.
Right now I am rendering those if I can find an user item on the localStorage:
`
Navbar.vue
<script>
export default {
data() {
return {
notLoggedInDropDown: false,
loggedInDropDown: false,
logged: localStorage.getItem('user') == null ? false : true,
user : {}
}
},
methods: {
closeSession() {
localStorage.removeItem('user');
localStorage.removeItem('token');
this.logged = false;
this.user = {};
},
},
mounted() {
var user = JSON.parse(localStorage.getItem('user'));
this.user = user;
},
}
</script>
And this is what I do after I login from the login page:
Login.vue
methods: {
async signIn(){
try {
const data = await login(this.username, this.password)
localStorage.setItem('user', JSON.stringify(data.user))
localStorage.setItem('token', data.token)
this.$router.push('/')
} catch (error) {
this.error.status = true
this.error.message = "Username or password failed."
}
}
},
`
I have tried to send emitters using mitt but navbar is not really a child component of the login page. I also have tried making the logged boolean a computed statement but it still does not re-render. I know that the reason it does not update is because the router.push method is not reactive, but I am unsure about what to try next. Also, my app does not use Vuex at the moment, can I integrate that easily into my Vue app? Any help welcome!
I think the best way is to use Vuex.
Create a variable in vuex, write it from Login.vue
and export it to all components throuht a getter. From Navbar.vue
you should get the vuex variable in a computed property and react to its value change when somebody logs in.
Otherwise, the recommended way to handle a login is through vue-router, you should take a look at the vue docs for it.
Good luck!