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():获取一个包含所有路由记录的数组。
相关推荐
广州智造9 分钟前
Radioss复合材料使用的单元属性
前端·设计·cad·建模·cae·radioss
张宏宇36 分钟前
我把微软开源的 tgrep 做成了本地版 GitHub Code Search:45,629 个文件里搜一次 10ms
前端·后端
huakoh42 分钟前
MCP 调用超时后别急着重试:三步读回分清执行状态
前端
打工仔折腾 AI43 分钟前
把模型切换交给平台:用蓝耘智能路由搭建商品评论分析工具
java·服务器·前端·后端·python·性能优化·ai agent 实战
不可能片场1 小时前
Electron 发布标题的冒号 击穿命令行解析
前端·electron
reeswell1 小时前
我开源了 inspect-devtools —— 让 AI 终于能"看见"你屏幕上的组件
前端·人工智能
Yuhano1 小时前
W3. 实现Agent工具调用引擎
前端·aigc·ai编程
flash俊杰1 小时前
第三节 基于 Vue 3 的领域模型架构——Schema 驱动的低代码后台实战
前端
热爱2331 小时前
dsh里使用chatgpt plus或pro会员而不是apikey,其实很简单。
前端·openai
linux_cfan1 小时前
videojs v10 源代码系列解读:32 · Reactor 模型:信号驱动的状态机
前端·javascript·音视频