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():获取一个包含所有路由记录的数组。
相关推荐
Marshmallowc1 分钟前
React useState 数据不同步?深度解析无限滚动中的“闭包陷阱”与异步更新丢失问题
前端·javascript·react.js·闭包·fiber架构
某柚啊1 分钟前
解决 minimatch 类型报错问题
前端·webpack·npm
前端 贾公子4 分钟前
npm 发包配置双重身份验证
前端·javascript·微信小程序·小程序·github
xkxnq13 分钟前
第四阶段:Vue 进阶与生态整合(第 48 天)(Vue 与 Axios 整合:实现 HTTP 请求的封装与拦截)
前端·vue.js·http
CappuccinoRose25 分钟前
React框架学习文档(三)
前端·react.js·ui·数组·标签·属性·jsx
LBJ辉29 分钟前
CSS - code
前端·css
旭日初扬29 分钟前
N32H762IIL调试中遇到的错误
前端
辰风沐阳31 分钟前
ES6 新特性: 解构赋值
前端·javascript·es6
猫头鹰源码(同名B站)33 分钟前
基于django+vue的时尚穿搭社区(商城)(前后端分离)
前端·javascript·vue.js·后端·python·django
weixin_4277716139 分钟前
npm 绕过2FA验证
前端·npm·node.js