devStandard/docs/learning/5-vue/2.1-add Routes注意.md
2025-03-29 14:35:49 +08:00

79 lines
2.0 KiB
Markdown
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 2.1-add Route注意
## 使用 addRoute 方法会有以下 bug
### 一、刷新浏览器回跳到404页面
#### 原因
```js
{ path: '*', redirect: '/404', hidden: true }
复制代码
```
404页面在静态路由里面动态路由拼接到动态路由后面因此会先进入404页面
#### 解决方案
把静态路由里面的 404路由规则删除 添加到动态路由最后面
```js
// router.addRoute([路由配置对象])
// 引入静态路由
import { constantRoutes } from '@/router/index'
// 根据角色作用有的权限来 过滤动态路由
const menus = store.state.user.userInfo.roles.menus
const filterasyncRoutes = asyncRoutes.filter(item => {
return menus.includes(item.children[0].name)
})
// 把 404 页面添加到最后面
filterasyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
router.addRoute(filterasyncRoutes)
await store.commit('menus/setMenusList', filterasyncRoutes)
```
### 二、刷新页面会白屏
解决方案
在路由前置守卫里面的 next() 里面添加
```js
if (store.state.user.userInfo.userId) {
next()
} else {
// ...
// 解决刷新出现的白屏bug
next({
...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
replace: true // 重进一次, 不保留重复历史
})
}
复制代码
```
### 三、菜单异常-控制台报错路由重复
#### 原因
路由设置是通过`router.addRoute(filterRoutes)`来添加的,退出时,并没有清空,再次登陆,又加了一次,所以有重复。
需要将路由权限重置 (恢复默认) 将来登录后再次追加才可以,不然的话,就会重复添加
#### 解决方案
```js
// 重置路由
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // 重新设置路由的可匹配路径
}
复制代码
```
> 这个方法就是将路由重新实例化,相当于换了一个新的路由,之前 **`加的路由`** 就不存在了,需要在 **登出的时候,调用一下即可**