Vue3-40-路由- 动态路由

说明

复制代码
本文主要介绍了 对路由的动态配置,主要包括以下几个部分:
	1、判断某个路由是否存在;
	2、查看路由对象中的所有路由配置;
	3、添加一个路由;
	4、删除一个路由。

针对上述四个方面,vue-router 中提供了对应的 API ,
因此,本文将主要介绍对应的API及其使用方法。

API 说明

注意 : 以下API 都是 全局路由配置对象的方法!
hasRoute(路由名称) : 判断某个路由是否存在,参数为 目标路由的名称,即 name 属性;
getRoutes(): 无参数,返回路由列表;
addRoute(): 添加路由
removeRoute(路由名称): 移除路由,参数为 目标路由的名称,即 name属性

下面介绍一下具体的使用

判断路由是否存在 hasRoute

ts 复制代码
  // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 判断是否存在某个路由 : 参数是路由的 name 
  console.log('判断是否包含 /a 路由 :',routerObj.hasRoute('aroute'))

获取路由的配置列表 getRoutes

ts 复制代码
 // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 查看所有的路由对象
  console.log('所有的路由配置列表 :',routerObj.getRoutes())

添加路由

常规添加

参数只有一个,就是目标路由配置对象

ts 复制代码
  // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 执行路由对象的添加
  routerObj.addRoute({
            path:'/c',
            name:'croute',
            component: () => import('./componentC.vue')
        })

添加路由到某个路由下成为子路由

参数有两个:
参数1 : 父级路由的 name
参数2 :目标路由的配置对象

ts 复制代码
  // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 添加嵌套路由
  routerObj.addRoute('aroute',{
            path:'c',
            name:'crouteChild',
            component: () => import('./componentC.vue')
        })

移除路由

根据路由名称执行移除

ts 复制代码
  // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 根据名称移除路由
  routerObj.removeRoute('aroute')

当路由没有name的时候该怎么办

复制代码
通常情况下,我们在路由配置的时候都会指定 【name】属性,
但是,在动态路由添加的时候,可能不会指定 【name】属性,
此时,就有了第二种的移除路由的方式,
那就是,在动态添加路由 addRoute() 的时候,会有一个返回值对象,
我们可以把这个返回值对象作为一个参数,调用一下,就会完成路由的移除动作。

代码如下:
ts 复制代码
  // 引入路由相关的方法
  import { useRouter} from 'vue-router';

  // 声明 路由实例对象 
  const routerObj = useRouter()

  // 接收一下 addRoute() 的回掉函数
  let routeCObj = routerObj.addRoute({
            path:'/c',
            name:'croute',
            component: () => import('./componentC.vue')
        })

  // 调用一下上面的回掉函数,对应的路由对象就被移除了
  routeCObj();
  // ok,完成移除操作
相关推荐
终端鹿10 小时前
Vue3 与第三方组件库联动:Element Plus 按需引入与二次封装
vue3·element plus·二次封装
Grocery store owner6 天前
vue3使用wangeditor上传附件以及添加表格,可以直接复制粘贴excel内容
vue3·wangeditor
floret. 小花6 天前
Vue3 知识点总结 · 2026-03-27
前端·面试·electron·学习笔记·vue3
梵得儿SHI7 天前
Vue 3 生态工具实战:UI 组件库与表单验证完全指南
前端·ui·vue3·elementplus·表单验证·antdesignvue·veevalidate
A_nanda8 天前
Vue项目升级
前端·vue3·vue2
创梦流浪人9 天前
soli-admin一款开箱即用的RBAC后台项目
java·spring boot·vue3·springsecurity
floret. 小花12 天前
Vue3 + Electron 知识点总结 · 2026-03-21
前端·面试·electron·学习笔记·vue3
木斯佳13 天前
前端八股文面经大全:小红书前端一二面OC(下)·(2026-03-17)·面经深度解析
前端·vue3·proxy·八股·响应式
沙振宇13 天前
【Web】使用Vue3+PlayCanvas开发3D游戏(六)模拟自驾场景SR+3D可视化
前端·游戏·3d·vue3·playcanvas
小鲤鱼ya13 天前
vue3 + ts + uni-app 移动端封装图片上传添加水印
前端·typescript·uni-app·vue3