跳到主要内容

addRoute

2023年05月28日
柏拉文
越努力,越幸运

一、认识


对路由的添加通常是通过 routes 选项来完成的,但是在某些情况下,你可能想在应用程序已经运行的时候添加或删除路由。具有可扩展接口(如 Vue CLI UI )这样的应用程序可以使用它来扩展应用程序。

addRoute() 用于动态添加路由。也就是说,如果新增加的路由与当前位置相匹配,就需要你用 router.push()router.replace() 来手动导航

二、语法


2.1 一级路由

const router = useRouter();

router.addRoute({ path: "/about" , name: "About", component: ""});

2.2 嵌套路由

const router = useRouter();

router.addRoute('About', { path: "/about" , name: "About", component: ""});

这等效于:

router.addRoute({
name: 'About',
path: '/about',
component: About,
children: [{ path: '/aboutChild', component: AboutChild }],
})

三、用法


3.1 页面动态添加

const router = useRouter();

router.addRoute({ path: "/about" , name: "About", component: ""});

页面仍然会显示之前组件,我们需要手动调用 router.replace() 来改变当前的位置,并覆盖我们原来的位置(而不是添加一个新的路由,最后在我们的历史中两次出现在同一个位置)。语法如下:

router.addRoute({ path: '/about', component: About })
// 我们也可以使用 this.$route 或 route = useRoute() (在 setup 中)
router.replace(router.currentRoute.value.fullPath)

记住,如果你需要等待新的路由显示,可以使用 await router.replace()

2.2 路由守卫动态添加

如果你决定在导航守卫内部添加或删除路由,你不应该调用 router.replace(), 而是通过返回新的位置来触发重定向:

router.beforeEach(to => {
if (!hasNecessaryRoute(to)) {
router.addRoute(generateRoute(to))
// 触发重定向
return to.fullPath
}
})