Home > Enterprise >  How to update navbar after a successful login in VueJS?
How to update navbar after a successful login in VueJS?

Time:12-15

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!

CodePudding user response:

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 throughtvue router, you should take a look at vue docs for it.

Good luck!

CodePudding user response:

There are three solutions I know to work. One is not rerouting with the vue-router but with the browser's functionality. Something like location.replace(url);. Two is working by emitting from the login page to the application and then using a prop giving the information to the navbar. Three and what i usually prefer using vuex to get a shared store between components. Option one is the easiest and fastest, but option three makes your application more robust.

  • Related