通常通过 routes 选项添加路由,但有时需要在应用已经运行后添加或删除路由。具有可扩展接口的应用,例如 Vue CLI UI,可以利用动态路由扩展应用。
添加路由
动态路由主要通过 router.addRoute() 和 router.removeRoute() 实现。它们只注册路由;如果新路由匹配当前位置,还需要用 router.push() 或 router.replace() 手动导航,才能显示新路由。来看一个例子:
假设路由器只有如下一个路由:
const router = createRouter({
history: createWebHistory(),
routes: [{ path: '/:articleName', component: Article }],
})
访问任何页面,例如 /about、/store 或 /3-tricks-to-improve-your-routing-code,最终都会显示 Article 组件。如果当前位于 /about,此时添加新路由:
router.addRoute({ path: '/about', component: About })
页面仍会显示 Article。需要手动调用 router.replace(),重新匹配当前位置并替换原历史记录,而不是新增记录、让同一位置在历史中出现两次:
router.addRoute({ path: '/about', component: About })
// 我们也可以使用 this.$route 或 useRoute()
router.replace(router.currentRoute.value.fullPath)
若需要等待新路由显示,可以使用 await router.replace()。
在导航守卫中添加路由
如果在导航守卫内部添加或删除路由,不应调用 router.replace(),而应返回新的位置触发重定向:
router.beforeEach(to => {
if (!hasNecessaryRoute(to)) {
router.addRoute(generateRoute(to))
// 触发重定向
return to.fullPath
}
})
此例有两个前提:新增路由记录会匹配 to 位置,从而改变该位置原先的匹配结果;添加新路由后,hasNecessaryRoute() 必须返回 true,以避免无限重定向。
因为发生了重定向,待执行的导航被替换,行为与前面的例子相同。实际应用中,更常见的是在导航守卫之外添加路由,例如视图组件挂载时注册新路由。
删除路由
可以用以下几种方法删除现有路由:
添加同名路由
添加与已有路由名称相同的路由时,会先删除原路由,再添加新路由:
router.addRoute({ path: '/about', name: 'about', component: About })
// 这将会删除之前已经添加的路由,因为他们具有相同的名字且名字必须是唯一的
router.addRoute({ path: '/other', name: 'about', component: Other })
调用添加路由返回的回调
const removeRoute = router.addRoute(routeRecord)
removeRoute() // 删除路由如果存在的话
路由没有名称时,这种方法尤其有用。
按名称移除路由
使用 router.removeRoute():
router.addRoute({ path: '/about', name: 'about', component: About })
// 删除路由
router.removeRoute('about')
如果希望按名称移除路由,同时避免名称冲突,可以用 Symbol 作为路由名称。
添加嵌套路由
要把嵌套路由加入已有路由,将父路由的 name 作为 router.addRoute() 的第一个参数。这等同于通过 children 添加子路由:
router.addRoute({ name: 'admin', path: '/admin', component: Admin })
router.addRoute('admin', { path: 'settings', component: AdminSettings })
等效写法是:
router.addRoute({
name: 'admin',
path: '/admin',
component: Admin,
children: [{ path: 'settings', component: AdminSettings }],
})
查看现有路由
Vue Router 提供两个方法:
router.hasRoute():检查路由是否存在。router.getRoutes():获取包含全部路由记录的数组。











暂无评论内容