先将路由拦截器代码贴上:
// 路由拦截器
router.beforeEach((to, from, next) => {
NProgress.start()
// 是否已经加载好路由列表
if (to.matched.length != 0) {
if (to.meta.requireAuth) {
// 判断该路由是否需要登录权限
if (Boolean(localStorage.getItem('userInfo'))) {
next()
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
} else {
if (Boolean(localStorage.getItem('userInfo'))) {
// 判断是否登录
if (to.path != '/' && to.path != '/login') {
//判断是否要跳到登录界面
next()
} else {
/**
* 防刷新,如果登录,修改路由跳转到登录页面,修改路由为登录后的首页
*/
next({
path: '/goods/Goods'
})
}
} else {
next()
}
}
} else {
//刷新后走的位置
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
})
刷新后发现match数组长度为0了,看了好多文章才知道是因为vueX刷新之后数据丢失造成路由列表数据丢失,所以匹配不到要进入的路由信息。
解决方法是在检测到数据丢失后重新请求添加路由列表,修改后的代码如下:
// 路由拦截器
router.beforeEach((to, from, next) => {
NProgress.start()
// 是否已经加载好路由列表
if (to.matched.length != 0) {
if (to.meta.requireAuth) {
// 判断该路由是否需要登录权限
if (Boolean(localStorage.getItem('userInfo'))) {
next()
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
} else {
if (Boolean(localStorage.getItem('userInfo'))) {
// 判断是否登录
if (to.path != '/' && to.path != '/login') {
//判断是否要跳到登录界面
next()
} else {
/**
* 防刷新,如果登录,修改路由跳转到登录页面,修改路由为登录后的首页
*/
next({
path: '/goods/Goods'
})
}
} else {
next()
}
}
} else {
//刷新后走的位置
// 修改:刷新后vuex内的路由列表数据丢失,重新获取路由列表再进行下一步
if (Boolean(localStorage.getItem('userInfo'))) {
store.dispatch('getRoutes').then(res => {
next()
})
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
})