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

关键点:

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值