vue-router添加动态路由及无限刷新白屏和添加不生效问题_router(2)

结尾

学习html5、css、javascript这些基础知识,学习的渠道很多,就不多说了,例如,一些其他的优秀博客。但是本人觉得看书也很必要,可以节省很多时间,常见的javascript的书,例如:javascript的高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

html5

    tmp.children = filterAsyncRoutes(tmp.children, roles)
  }
  res.push(tmp)
}

})

return res
}

export default {
namespaced: true,
state,
mutations,
actions
}


* src/permission.js



> 
> 修改根目录src下的permission.js
> 
> 
> 



if (hasToken) {
if (to.path === ‘/login’) {
next({ path: ‘/’ })
NProgress.done()
} else {
try {
const roles = await store.dispatch(‘user/getInfo’)
await store.dispatch(‘permission/generateRoutes’, roles).then(res => {
router.addRoutes(res)
next({ …to, replace: true })
})
} catch (error) {
await store.dispatch(‘user/resetToken’)
Message.error(error || ‘Has Error’)
next(/login?redirect=${to.path})
NProgress.done()
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(/login?redirect=${to.path})
NProgress.done()
}
}


## 问题一:路由守卫死循环


![在这里插入图片描述](https://img-blog.csdnimg.cn/20210301143610569.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk5MzA2NQ==,size_16,color_FFFFFF,t_70)



> 
> 如图,按上面配置动态路由后,在进入路由守卫时,不断循环,无法正常转发
> 
> 
> 


其实在路由守卫中,只有`next()`是放行,其他的诸如:`next('/logon') 、 next(to) 或者 next({ ...to, replace: true })`都不是放行,而是:**中断当前导航,执行新的导航**


例如现在我有一个守卫,在守卫中我使用`next('/logon')`,肯定有同学认为是会直接跳转到/logon路由:



beforeEach((to, from, next) => {
next(‘/logon’)
}


其实他是这么执行的:



beforeEach((to, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEac… // 一直循环下去… , 因为我们没有使用 next() 放行
}
}
}
}


`next('/logon')`不是说直接去`/logon`路由,而是中断这一次路由守卫的操作,又进入一次路由守卫,就像嵌套一样,一层路由守卫,然后又是一层路由守卫,此时路由守卫进入到第二层时,`to.path`已经不是`/home`了,这个时候才执行`next()`放行操作。  
 如果守卫中没有正确的放行出口的话,会一直`next({ ...to})`进入死循环 !!!


因此你还需要确保在当`addRoutes()`已经完成时,所执行到的这一次`beforeEach((to, from, next)`中有一个正确的`next()`方向出口。  
 **因此想实现动态添加路由的操作的话,代码应该是这样的:**



const hasToken = getToken()[‘Authorization’]
if (hasToken) {
if (to.path === ‘/login’) {
next({ path: ‘/’ })
NProgress.done()
} else {
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if(hasRoles){
next()
}else{
try {
const roles = await store.dispatch(‘user/getInfo’)
await store.dispatch(‘permission/generateRoutes’, roles).then(res => {
router.addRoutes(res)
next({ …to, replace: true })
})
} catch (error) {
await store.dispatch(‘user/resetToken’)
Message.error(error || ‘Has Error’)
next(/login?redirect=${to.path})
NProgress.done()
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(/login?redirect=${to.path})
NProgress.done()
}
}
})



getInfo({ commit, state }){
return new Promise((resolve, reject) => {
const { roles } = JSON.parse(getUser())
commit(“SET_ROLES”, roles)
resolve(roles)
})
},


## 问题二:addRouters()不生效



> 
> 执行完addRouters()后,我查看了store里的routes,已经有将动态路由添加进去,但是菜单中还是没有显示
> 
> 
> 



> 
> 查看了/layout/components/Sidebar/index.vue,发现使用的是this. 
>  
>  
>  
>  
>  r 
>  
>  
>  o 
>  
>  
>  u 
>  
>  
>  t 
>  
>  
>  e 
>  
>  
>  r 
>  
>  
>  . 
>  
>  
>  o 
>  
>  
>  p 
>  
>  
>  t 
>  
>  
>  i 
>  
>  
>  o 
>  
>  
>  n 
>  
>  
>  s 
>  
>  
>  . 
>  
>  
>  r 
>  
>  
>  o 
>  
>  
>  u 
>  
>  
>  t 
>  
>  
>  e 
>  
>  
>  s 
>  
>  
>  而 
>  
>  
>  不 
>  
>  
>  是 
>  
>  
>  s 
>  
>  
>  t 
>  
>  
>  o 
>  
>  
>  r 
>  
>  
>  e 
>  
>  
>  中 
>  
>  
>  的 
>  
>  
>  , 
>  
>  
>  所 
>  
>  
>  以 
>  
>  
>  我 
>  
>  
>  们 
>  
>  
>  需 
>  
>  
>  要 
>  
>  
>  在 
>  
>  
>  a 
>  
>  
>  d 
>  
>  
>  d 
>  
>  
>  R 
>  
>  
>  o 
>  
>  
>  u 
>  
>  
>  t 
>  
>  
>  e 
>  
>  
>  r 
>  
>  
>  s 
>  
>  
>  ( 
>  
>  
>  ) 
>  
>  
>  后 
>  
>  
>  也 
>  
>  
>  修 
>  
>  
>  改 
>  
>  
>  t 
>  
>  
>  h 
>  
>  
>  i 
>  
>  
>  s 
>  
>  
>  . 
>  
>  
>  
>  router.options.routes而不是store中的,所以我们需要在addRouters()后也修改this. 
>  
>  
>  router.options.routes而不是store中的,所以我们需要在addRouters()后也修改this.router.options.routes的值,或者直接修改下面routes()方法,直接使用store中的routes
> 
> 
> 



routes() {
return this.$router.options.routes
}


**修改后的permission.js**



const roles = await store.dispatch(‘user/getInfo’)
await store.dispatch(‘permission/generateRoutes’, roles).then(res => {
router.addRoutes(res)
router.options.routes = store.getters.routes
next({ …to, replace: true })
})


## 最终版,所有相关文件


* router/index.js



import Vue from ‘vue’
import Router from ‘vue-router’
import Layout from ‘@/layout’

Vue.use(Router)

export const constantRoutes = [
{
path: “”,
redirect: ‘/portal’,
},

{
path: ‘/login’,
component: () => import(‘@/views/login/index’),
},

{
path: ‘/404’,
component: () => import(‘@/views/404’),
},

{
path: ‘/portal’,
component: () => import(‘@/views/portal/index’),
},

{
path: ‘/’,
component: Layout,
redirect: ‘/dashboard’,
children: [{
path: ‘dashboard’,
name: ‘Dashboard’,
component: () =>
import (‘@/views/dashboard/index’),
meta: { title: ‘资源认证平台’, affix: true, icon: ‘dashboard’ }
}]
},

{
path: ‘/user’,
component: Layout,
redirect: ‘/user’,
children: [{
path: ‘user’,
name: ‘User’,
component: () =>
import (‘@/views/user/index’),
meta: { title: ‘用户管理’, affix: true, icon: ‘user’, }
}]
}
// 404 page must be placed at the end !!!
]

export const asyncRoutes = [
{
path: ‘/application’,
component: Layout,
redirect: ‘/application’,
children: [{
path: ‘application’,
name: ‘Application’,
component: () =>
import (‘@/views/application/index’),
meta: { title: ‘应用管理’, affix: true, icon: ‘table’, roles: [‘system’] }
}]
},
{ path: ‘*’, redirect: ‘/404’, hidden: true }
]

const createRouter = () => new Router({
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})

const router = createRouter()

export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}

export default router


* store/modules/permission.js




### 自学几个月前端,为什么感觉什么都没学到??

----------------------------------------------------------------------------------

这种现象在很多的初学者和自学前端的同学中是比较的常见的。

因为自学走的弯路是比较的多的,会踩很多的坑,学习的过程中是比较的迷茫的。

最重要的是,在学习的过程中,不知道每个部分该学哪些知识点,学到什么程度才算好,学了能做什么。

很多自学的朋友往往都是自己去找资料学习的,资料上有的或许就学到了,资料上没有的或许就没有学到。



这就会给人一个错误的信息就是,我把资料上的学完了,估计也-就差不多的了。

但是真的是这样的吗?非也,因为很多人找的资料就是很基础的。学完了也就是掌握一点基础的东西。分享给你一份前端分析路线,你可以参考。

**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0)**

![](https://img-blog.csdnimg.cn/img_convert/15be8206a9f6e5bd9e8e930303b613ee.png)



还有很多的同学在学习的过程中一味的追求学的速度,很快速的刷视频,写了后面忘了前面,最后什么都没有学到,什么都知道,但是什么都不懂,要具体说,也说不出个所以然。



所以学习编程一定要注重实践操作,练习敲代码的时间一定要多余看视频的时间。



在学习的过程中,不知道每个部分该学哪些知识点,学到什么程度才算好,学了能做什么。

很多自学的朋友往往都是自己去找资料学习的,资料上有的或许就学到了,资料上没有的或许就没有学到。



这就会给人一个错误的信息就是,我把资料上的学完了,估计也-就差不多的了。

但是真的是这样的吗?非也,因为很多人找的资料就是很基础的。学完了也就是掌握一点基础的东西。分享给你一份前端分析路线,你可以参考。

**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0)**

![](https://img-blog.csdnimg.cn/img_convert/15be8206a9f6e5bd9e8e930303b613ee.png)



还有很多的同学在学习的过程中一味的追求学的速度,很快速的刷视频,写了后面忘了前面,最后什么都没有学到,什么都知道,但是什么都不懂,要具体说,也说不出个所以然。



所以学习编程一定要注重实践操作,练习敲代码的时间一定要多余看视频的时间。



  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值