Vue Router无法呈现正确的组件

时间:2018-07-10 06:45:51

标签: javascript vue.js vuejs2 vue-component vue-router

我在vue-router中有一些嵌套的路由,可以在router.js中找到。但是,每次我登录用户时,Query中的ResultHeader链接总是呈现RegisterLogin组件,但是我可以确认我的通过{strong> vue开发人员工具进行调查,Vuex具有正确的令牌设置。


因此,我对vue-router起作用的期望如下:

  1. 用户尝试登录/user/login
  2. 登录成功,令牌设置为Vuex状态
  3. 用户被重定向到/
  4. 用户单击/queryresult链接,<router-view>渲染Query中的ResultApp.vue组件。
  5. 用户单击Logout按钮,Vuex状态被清除。
  6. 用户被重定向回/user/login

但是我得到的结果是:

  1. 用户尝试登录/user/login
  2. 登录成功,令牌设置为Vuex状态
  3. 用户被重定向到/
  4. 用户单击/query链接,<router-view>中的App.vue呈现了Register组件。
  5. 用户单击/result链接,<router-view>中的App.vue呈现了Login组件。
  6. 用户使用F5刷新页面。
  7. 用户单击/queryresult链接,<router-view>渲染Query中的ResultApp.vue组件。
  8. 用户单击Logout按钮,Vuex状态被清除。
  9. 用户被重定向回/user/login
  10. 用户单击Login按钮,<router-view>中的App.vue呈现了Result组件。

我尝试过的

  1. 删除路由上的令牌保护,<router-view>仍然无法呈现正确的组件。
  2. 在令牌保护仍处于启用状态的情况下,从所有v-if="auth"中删除<router-link>,问题似乎消失了。但是我只想在用户登录时呈现QueryResult,反之亦然。
  3. 使用v-show代替v-if可以解决此问题,但是我怀疑这是隐藏用户链接的正确方法。
  4. 命名所有路由,但问题仍然存在。

某些代码

这是我的router.js

import User from './components/user/User'
import Home from './components/Home'
import Login from './components/user/Login'
import Register from './components/user/Register'
import Query from './components/Query'
import Result from './components/result/Result'
import List from './components/result/List'
import Display from './components/result/Display'

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

const router = [
    {
        path: '/', name: 'home', component: Home
    },
    {
        path: '/user', component: User, children: [
            {path: 'login', component: Login},
            {path: 'register', component: Register},
        ]
    },
    {
        path: '/query', name: 'query', component: Query
    },
    {
        path: '/result', component: Result, children: [
            {path: '', component: List},
            {path: ':token', component: Display}
        ]
    },
    {path: '*', redirect: '/'},
];

export default new VueRouter({
    routes: router,
    mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        }
        if (to.hash) {
            return {selector: to.hash};
        }
        return {x: 0, y: 0};
    }
})

这是我的Header.vue

<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">
                    <a class="nav-link">Register</a>
                </router-link>
                <router-link to="/user/login" active-class="active" tag="li" v-if="!auth">
                    <a class="nav-link">Login</a>
                </router-link>
                <router-link to="/query" active-class="active" tag="li" v-if="auth">
                    <a class="nav-link">Query</a>
                </router-link>
                <router-link to="/result" active-class="active" tag="li" v-if="auth">
                    <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>

这是我的App.vue

<template>
    <div>
        <appHeader></appHeader>
        <div class="container">
            <router-view></router-view>
        </div>
        <appFooter></appFooter>
    </div>
</template>

<script>
    import Header from './components/layouts/Header'
    import Footer from './components/layouts/Footer'

    export default {
        components: {
            'appHeader': Header,
            'appFooter': Footer
        }
    }
</script>

这是我的store/store.js

import Vue from 'vue';
import Vuex from 'vuex';

import actions from './actions';
import getters from './getters';
import mutations from './mutations';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        jwt: {
          token: null,
          expire: null
        },      
    },
    getters,
    mutations,
    actions,
});

这是我的store/actions.js

import * as types from './types';
import axios from '../axios';
import router from '../router'

export default {
    [types.ACTION_USER_LOGIN]: ({commit, dispatch}, payload) => {
        axios.post('/api/user/login/', {
            email: payload.email,
            password: payload.password,
        })
            .then(res => {
                if (Object.keys(res.data).length === 0 && res.data.constructor === Object) {
                    return
                }
                let payload = {
                    'token': res.data.token,
                    'expire': new Date(res.data.expire_on * 1000)
                };

                dispatch(types.ACTION_SET_TOKEN, payload);
                commit(types.MUTATE_UPDATE_JWT, payload);
                router.push('/')
            })
            .catch(error => {
                console.log(error);
            })
    },
    [types.ACTION_USER_REGISTER]: ({commit, dispatch}, payload) => {
        axios.post('/api/user/register/', {
            email: payload.email,
            password: payload.password
        }).then(res => {
            if (Object.keys(res.data).length === 0 && res.data.constructor === Object) {
                return
            }
            let payload = {
                'token': res.data.token,
                'expire': new Date(res.data.expire_on * 1000)
            };
            dispatch(types.ACTION_SET_TOKEN, payload);
            commit(types.MUTATE_UPDATE_JWT, payload);
            router.push('/')
        }).catch(error => {
            console.log(error);
        })
    },
    [types.ACTION_USER_LOGOUT]: ({commit, dispatch}) => {
        dispatch(types.ACTION_CLEAR_TOKEN);
        commit(types.MUTATE_CLEAR_AUTH);
        router.push("/user/login");
    },
    [types.ACTION_CLEAR_TOKEN]: () => {
        localStorage.removeItem('jwt_token');
        localStorage.removeItem('jwt_expire');
    },
    [types.ACTION_SET_TOKEN]: ({commit}, payload) => {
        localStorage.setItem("jwt_token", payload.token);
        localStorage.setItem("jwt_expire", payload.expire);
    }     
};

这是我的store/getters.js

import * as types from './types';

export default {
    [types.GETTER_IS_AUTHENTICATED]: state => {
        return state.jwt.token !== null
    }
};

这是我的store/mutations.js

将*作为'./types'中的类型导入;

export default {
    [types.MUTATE_UPDATE_JWT]: (state, payload) => {
        state.jwt = payload
    },
    [types.MUTATE_CLEAR_AUTH]: (state) => {
        state.jwt.token = null;
        state.jwt.expire = null;
    },
};

这是我的axios.js自定义实例

import {store} from './stores/store'
import axios from 'axios'

const instance = axios.create({
    baseURL: 'http://127.0.0.1:8000',
    withCredentials: true
});

instance.interceptors.request.use(config => {
    if (store.state.jwt.token != null) {
        config.headers.common['Authorization'] = 'Bearer ' + store.state.jwt.token;
    }
    return config;
});

export default instance

我的store/types.js包含所有常量变量字符串,因此我认为没有必要在此处包含

请让我知道是否需要提供有关该问题的更多信息。

1 个答案:

答案 0 :(得分:0)

我通过为key中的每个router-link分配一个唯一的Header.vue来解决了这个问题。因此,修改后的最终Header.vue文件如下所示:

<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>

在没有v-if的每个router-link中没有关联密钥的情况下,VueJS似乎无法正确更新DOM。