VueRouter 动态路由

通常情况下我们是在routes选项中定义路由跳转规则

另外我们可以使用VueRouter提供的API进行添加和删除路由

添加路由 router.addRoute()

注意:

1. 默认情况每次使用addRouter只能注册一个新的路由

2. 如果新增路由与当前位置路由相匹配,想要显示新的路由,需要手动使用router.push()router.replace() 进行导航跳转              

// 配置路由规则
const router = createRouter({
    history: createWebHistory(),
    routes: [{path: '/:articleName',component: Article}],
})


// 使用 addRouter() 新注册一个路由
router.addRouter({ path:'/about', component: About})  // 如果此时我们所在路由与当前新增路由相匹配,只会停留在当前路由,无法显示新的路由。 需要我们使用router.replace()或router.push() 手动导航

// 避免在history中出现两次重复地址,我们使用router.replace() 替换之前的地址
router.replace('/about')

// 注意:如果我们需要等待新的路由显示 可以使用await router.replace()

 

在导航守卫中添加路由

如果你决定在路由守卫内部添加或删除路由,你不应该调用router.replace(),而是使用return 返回新的位置在触发重定向

router.beforeEach(to=>{
 // 避免无线重定向        
 if(!hasNecessaryRoute(to)){
   router.addRoute(generateRoute(to))
   return to.fullPath
 }
})

删除路由 router.removeRoute()

第一种删除:通过添加一个名称冲突的路由。如果添加与现有途径名称相同的路径,会先删除路由,在添加路由

// 添加一个name为about的路由
router.add({path: '/about', name: 'about', component: About})

// 添加重复name的路由,但是组件不同
// 这将会删除之前已经添加的路由,因为他们具有相同的名字且名字必须是唯一的 
router.add({path: '/about', name: 'about', component: Other}) 

第二种删除:通过router.addRoute() 返回的回调

const removeRoute = router.addRoute(routeRecode)
removeRoute() // 删除路由如果存在的话 注意:适合删除没有名称的路由

第三种删除:通过router.removeRoute() 按照名称删除

router.addRoute({path: '/about', name:'about', component: About})
// 删除路由 如果想避免名字的冲突,可以在路由中使用Symbol作为名字
router.removeRoute('about') // 注意:删除该路由的话,其所有的别名和子路由都会被同时删除    

添加嵌套路由

router.addRoute({name:'father', path:'/fatherPath', component: Father})

// 如果想添加嵌套路由 则可以通过指定name 进行嵌套添加
router.addRoute({'father',{path: 'sonPath', component: Son}})


// 等效于
router.addRoute({
 name: 'father',
 path: '/fatherPath',
 component: Father,
 children: [{path: 'sonPath', component: Son}}]
})

查看现有的路由

VueRouter 提供了两个功能来查看现有的路由
* router.hashRoute() :检查路由已存在

* router.getRoutes() :获取一个包含所有路由记录的数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值