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():获取一个包含所有路由记录的数组。
相关推荐
答案answer13 分钟前
一些经典的3D编辑器开源项目
前端·开源·three.js
亿元程序员29 分钟前
Creator都快4.0了,怎么能没有这样的功能?
前端
q***649731 分钟前
SpringMVC 请求参数接收
前端·javascript·算法
万少35 分钟前
流碧卡片 6 小时闪电开发 AI gemini-3-pro-preview ! 秒出小红书爆款图,免下载直接用
前端·后端·ai编程
向葭奔赴♡1 小时前
若依系统权限控制全流程解析
前端·javascript·vue.js·ruoyi·navicat
IT_陈寒1 小时前
Python开发者必知的5个高效技巧,让你的代码性能提升50%
前端·人工智能·后端
u***u6851 小时前
Vue虚拟现实案例
前端·vue.js·vr
q***96581 小时前
springboot3整合knife4j详细版,包会!(不带swagger2玩)
android·前端·后端
艾小码1 小时前
Vue 3 defineProps 与 defineEmits 深度解析
前端·javascript·vue.js
巧克力芋泥包5 小时前
前端使用阿里云图形验证码;并且与安卓进行交互
android·前端·阿里云