[Vuejs]-Vue Router does not render correct component

0👍

I have solved the issue by assigning a unique key to every router-link in Header.vue. So the final Header.vue file looks like this after modifications:

<template>
    <nav class="navbar navbar-expand-lg navbar-light bg-light" id="header">
        <a class="navbar-brand" href="#">CMAP</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav ml-auto">
                <router-link to="/user/register" active-class="active" tag="li" v-if="!auth" key="link_reg">
                    <a class="nav-link">Register</a>
                </router-link>
                <router-link to="/user/login" active-class="active" tag="li" v-if="!auth" key="link_login">
                    <a class="nav-link">Login</a>
                </router-link>
                <router-link to="/query" active-class="active" tag="li" v-if="auth" key="link_query">
                    <a class="nav-link">Query</a>
                </router-link>
                <router-link to="/result" active-class="active" tag="li" v-if="auth" key="link_result">
                    <a class="nav-link">Result</a>
                </router-link>
                <li @click="logout" class="nav-item" v-if="auth">
                    <a class="nav-link">Logout</a>
                </li>
            </ul>
        </div>
    </nav>
</template>

<script>
    import * as  types from '../../stores/types'

    export default {
        methods: {
            logout() {
                // clear state.token and redirect user to '/user/login'
                this.$store.dispatch(types.ACTION_USER_LOGOUT);
            }
        },
        computed: {
            auth() {
                // return true if state.token is set in vuex
                return this.$store.getters[types.GETTER_IS_AUTHENTICATED]
            }
        }
    }
</script>

It seems that VueJS couldn’t update the DOM properly without associated key in each v-if for router-link.

👤Woody

Leave a comment