项目中往往都是添加动态路由,如何删除已经添加进来的路由往往被忽视,为此这里做一下记录:
查看vue-router路由文档 可以看出 Vue2中是通过matcher来进行重新赋值来进行清空的。
- let createRouter = () => new Router({
- mode: 'history', //hash history后端支持可开,需配置nginx, 次模式下不会再返回404界面
- routes: constantRouterMap, // 路由路径
- scrollBehavior: () => ({ y: 0 }) // 在切换时定位路由滚动条的位置
- });
-
- const router = createRouter()
-
- export function resetRouter () { //清空路由的方法
- const newRouter = createRouter()
- router.matcher = newRouter.matcher
- }
- export default router;
而Vue3中没有关于matcher这个属性,这样一来,就需要自己通过循环遍历来清除路由,
- const router = createRouter({
- routes,
- history: createWebHashHistory()
- })
- console.log(router.getRoutes());
-
- //重置路由
- export function resetRouter(){
- let routers = router.getRoutes()
- console.log(routers);
- routers.map((it:any)=>{
- if(!whiteList.includes(it.name)){
- router.removeRoute(it.name)
- }
- })
- console.log(routers);
- }
** 注:whiteList是白名单,