vue路由報錯Navigating to current location ("/login") is not allowed踩坑總結

.在我添加“未登錄”判斷後,想自動跳轉到登錄頁。但是遇到了問題:

Navigating to current location ("/login") is not allowed

不停的報錯:

 

 

 

背景:

我在main.js裏面寫了判斷路由跳轉。

 

 

解決辦法:

網上說:

在路由跳轉的時候同一個路由多次添加是不被允許的

 

 

所以最後:

代碼:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'
import qs from 'qs'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import global from './Global'
import vueAplayer from 'vue-aplayer'
import Router from 'vue-router';

Vue.prototype.GLOBAL = global
axios.defaults.baseURL = global.BASE_URL
axios.defaults.withCredentials = true

Vue.prototype.$axios = axios

Vue.use(Router,vueAplayer, VueAxios, axios, qs)
// 全局配置:完整引入 Element:
Vue.use(ElementUI, {size: 'small', zIndex: 3000});
Vue.config.productionTip = false;

//在路由跳轉的時候同一個路由多次添加是不被允許的
//重寫路由的push方法
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
    return VueRouterPush.call(this, to).catch(err => err)
}

//在路由跳轉之前判斷,除了首頁以外,其他頁面必須登錄才能訪問,異步問題
router.beforeEach((to, from, next) => {
    if (to.path === '/' || to.path === '/login' || to.path === '/activate' || to.path === '/register') {
        next();
    } else {
        axios.get("/user/isLogin")
            .then(response => {
                console.log(response.data);
                let data = response.data;
                if (data.status === global.responseCode.OK && data.result === true) {
                    console.log("登錄成功");
                    next();
                } else {
                    next('/login?redirect=' + to.path);
                }
            });
    }
});

new Vue({
    router,
    // render函數是渲染一個視圖,然後提供給el掛載,如果沒有render那頁面什麼都不會出來
    //components: { App }  vue1.0的寫法
    // render: h => h(App)    vue2.0的寫法
    render: h => h(App),
    template: '<App/>',
}).$mount('#app')

 

 

關鍵點:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章