How to hide login route navigation element after user has logged in using token authentication?

Viewed 581

On login, I save the token in the local storage using localStorage.setItem('token', token); but now I would like to hide the navigation elements that leads to the login and signup routes. These are my routes:

<template>
    <div class="nav-header">
        <div class="wrapper">
            <ul class='nav-ul'>
                <router-link to="/" tag='li' active-class='active' exact><li><a>Home</a></li></router-link>
                <router-link to="/signup" tag='li' active-class='active' exact><li><a>Sign Up</a></li></router-link>
                <router-link to="/signin" tag='li' active-class='active' exact><li><a>Sign In</a></li></router-link>
            </ul>
        </div>
    </div>
</template>

I assume I need to check if I have a stored token in my local storage and hide the routes if I do.

1 Answers

You can define a computed property in your component, for example, isLoggedIn which returns a boolean value.

computed: {
  isLoggedIn() {
    return !!window.localStorage.getItem('token')
  }
}

You can then use the v-if directive in the routes that you want to hide.

<template>
    <div class="nav-header">
        <div class="wrapper">
            <ul class='nav-ul'>
                <router-link to="/" tag='li' active-class='active' exact><li><a>Home</a></li></router-link>
                <router-link to="/signup" v-if="!isLoggedIn" tag='li' active-class='active' exact><li><a>Sign Up</a></li></router-link>
                <router-link to="/signin" v-if="!isLoggedIn" tag='li' active-class='active' exact><li><a>Sign In</a></li></router-link>
            </ul>
        </div>
    </div>
</template>
Related