vue路由报错Navigating to current location ("/login") is not allowed踩坑总结

.在我添加“未登录”判断后,想自动跳转到登录页。但是遇到了问题:

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

不停的报错:

 

vue路由报错Navigating to current location (

 

 

背景:

我在main.js里面写了判断路由跳转。

 

 

解决办法:

网上说:

在路由跳转的时候同一个路由多次添加是不被允许的

 

vue路由报错Navigating to current location (

 

所以最后:

代码:

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: '',
}).$mount('#app')

 

 

关键点:

vue路由报错Navigating to current location (

 

最开始写在main.js里面的。结果还是出问题了。然后我就把关键内容。剪切到index.js里面就好了!

vue路由报错Navigating to current location (

你可能感兴趣的:(vuejs)