项目一般都会用到路由守卫,给一些需要登录的页面,做权限认证,只有登陆了才可以进去
今天遇到的问题是路由跳转错误
在我写路由前置守卫的时候,发生了如下报错
我这边写的登录逻辑是
先创建一个路由前置守卫,
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import store from '@/store'
import { Dialog } from 'vant';
router.beforeEach((to, from, next) => {
})
然后根据是否登录了,在做具体的事情
如果登录了,
想去哪,就去哪里。
如果没登录,是否是去要权限认证的页面,是的话,去登录页,并且把跳转前的路径留下,方便路由跳转之后再回去,这样用户体验好得多。
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import store from '@/store'
import { Dialog } from 'vant';
router.beforeEach((to, from, next) => {
if (store.state.token) {
//在这里做登录了的事情
return next()
} else {
//在这里做没登录的事情
}
})
//在这里我给需要权限认证的地方,添加了meta对象,进行了标记
//在这里我给需要权限认证的地方,添加了meta对象,进行了标记
const routes = [
///...
{
path: '/goinfo',
component: () => import('@/views/search/goinfo.vue')
},
{
path: '/canav',
name: 'canav',
component: () => import('@/views/canav'),
meta: { requiresAuth: true }
}
//...
]
全局则是这样:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import store from '@/store'
import { Dialog } from 'vant';
const routes = [
{
path: '/login',
component: () => import('@/views/login/')
},
{
path: '/',
component: () => import('@/views/layout/index.vue'),
redirect: '/home',
children: [
{
path: '/home',
component: () => import('@/views/home/index.vue')
},
{
path: '/my',
component: () => import('@/views/my/index.vue')
},
]
},
{
path: '/goinfo',
component: () => import('@/views/goinfo/index.vue')
},
{
path: '/canav',
name: 'canav',
component: () => import('@/views/canav'),
meta: { requiresAuth: true }
}
]
const router = new VueRouter({
routes
})
// router.beforeEach((to, from, next) => {
// if (to.name === 'login' || !to.meta.requiresAuth) {
// return next()
// }
// if (store.state.user) {
// return next()
// }
// Dialog.confirm({
// title: '该功能需要登录,确认登录吗?'
// }).then(() => {
// next({
// name: 'login',
// query: {
// redirect: from.fullPath
// }
// })
// }).catch(() => {
// // on cancel
// })
// if (store.state.user) {
// return next()
// }
// })
//自己完成一次
//处理逻辑 如果登录了,就去登录页面,
// 如果没有登录,你是去要有权限的页面吗?是,去登录页,并且留下地址,方便登录后返回,如果不是去有权限的页面,想去哪就去哪
// next()表示放行 路由包3.1版本可以,之前3.5版本直接报错,给路由降级
router.beforeEach((to, from, next) => {
if (store.state.user) {
return next()
} else {
if (to.meta.requiresAuth) {
// console.log('我要权限,来的时候的路由', from.fullPath);
// console.log('我要权限,去的时候的路由', to.fullPath);
// console.log('qa进不去,我要去登录页');
Dialog.confirm({
title: '该功能需要登录,确认登录吗?'
}).then(() => {
next({
path: '/login',
query: {
redirect: to.fullPath,
}
})
}).catch(() => {
//取消路由的跳转
next(false)
})
} else {
// console.log('我在去登录页的路上');
// console.log(to.path);
next()
}
}
})
export default router
这里我检查了很久,确定代码没问题,可是报错一直无法解决,这里我查看了其他博客,
发现引起的原因之一是,路由版本太高,可以降低版本,看看能否解决。
我的路由是,vue-cli脚手架创建的,于是,我把路由降级
果真,问题就完美解决啦。