vue3之动态路由

添加路由

javascript 复制代码
const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/about', component: Article }],
})
//页面仍然会显示 Article 组件
router.addRoute({ path: '/about', component: About })

//我们需要手动调用 router.replace() 来改变当前的位置,并覆盖我们原来的位置
// 我们也可以使用 this.$route 或 route = useRoute() (在 setup 中)
router.replace(router.currentRoute.value.fullPath)

等待新的路由显示,可以使用 await router.replace()

在导航守卫中添加路由

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

javascript 复制代码
router.beforeEach(to => {
  //hasNecessaryRoute() 在添加新的路由后返回 false,以避免无限重定向。
  if (!hasNecessaryRoute(to)) {
    router.addRoute(generateRoute(to))
    // 触发重定向
    return to.fullPath
  }
})

删除路由

javascript 复制代码
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 作为名字

添加嵌套路由

javascript 复制代码
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 }],
})

查看现有路由

  • router.hasRoute():检查路由是否存在。
  • router.getRoutes():获取一个包含所有路由记录的数组。
相关推荐
月忆36425 分钟前
等待组(waitgroup)
前端·爬虫·python
令狐寻欢28 分钟前
HTML中 的 meta 标签常用属性及其作用
前端·html
SynthWriter33 分钟前
Trae 帮我生成了一个贪吃蛇的游戏,好玩儿
前端
用户21411832636021 小时前
dify案例分享-Dify+RSS 聚合 8 大平台实时热点,新闻获取效率飙升 300%
前端
百锦再1 小时前
Razor编程中@Html的方法使用大全
前端·html
啪叽1 小时前
JavaScript可选链操作符(?.)的实用指南
前端·javascript
Ian在掘金1 小时前
bat+python实现easy connect自动连接
前端·python
代码搬运媛1 小时前
【react实战】如何实现监听窗口大小变化
前端·javascript·react.js
小桥风满袖1 小时前
Three.js-硬要自学系列30之专项学习环境光
前端·css·three.js
Luckyfif1 小时前
🤯由 性能指标 散发开来的 Performance API 被问爆了呀
前端·面试·性能优化