vue3之动态路由

添加路由

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(),而是通过返回新的位置来触发重定向

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

删除路由

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 作为名字

添加嵌套路由

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():获取一个包含所有路由记录的数组。

相关推荐

  1. vue3动态

    2024-03-26 23:44:01       36 阅读
  2. vue3带参数的动态

    2024-03-26 23:44:01       45 阅读
  3. Vue3-40-- 动态

    2024-03-26 23:44:01       48 阅读
  4. vue3如何实现动态

    2024-03-26 23:44:01       67 阅读
  5. Vue 3 嵌套

    2024-03-26 23:44:01       37 阅读
  6. vue3导航故障

    2024-03-26 23:44:01       39 阅读
  7. vue3+vite动态的实现方式

    2024-03-26 23:44:01       66 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-26 23:44:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-26 23:44:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-26 23:44:01       82 阅读
  4. Python语言-面向对象

    2024-03-26 23:44:01       91 阅读

热门阅读

  1. Python networkx库中,G.add_edge方法的原理和使用方法

    2024-03-26 23:44:01       37 阅读
  2. 【CSP试题回顾】201912-2-回收站选址(优化)

    2024-03-26 23:44:01       39 阅读
  3. My SQL 子查询

    2024-03-26 23:44:01       46 阅读
  4. MySQL写shell的问题

    2024-03-26 23:44:01       41 阅读
  5. MySQL数据库索引失效的常见情况

    2024-03-26 23:44:01       44 阅读
  6. 构建一个springboot项目

    2024-03-26 23:44:01       43 阅读
  7. macOS Sonoma 14.4.1(23E224)发布(附黑/白苹果镜像)

    2024-03-26 23:44:01       33 阅读
  8. js的变量

    2024-03-26 23:44:01       42 阅读
  9. 每天一个数据分析题(二百三十一)

    2024-03-26 23:44:01       42 阅读
  10. Xilinx缓存使用说明和测试

    2024-03-26 23:44:01       33 阅读
  11. 浅谈uniapp优缺点

    2024-03-26 23:44:01       39 阅读
  12. 验证回文串

    2024-03-26 23:44:01       39 阅读