【Vue-Router】动态路由

对路由的添加通常是通过 routes 选项来完成的,但是在某些情况下,你可能想在应用程序已经运行的时候添加或删除路由,此时可以使用动态路由。

添加路由

动态路由主要通过两个函数实现。router.addRoute() 和 router.removeRoute()。它们只注册一个新的路由,也就是说,如果新增加的路由与当前位置相匹配,就需要你用 router.push() 或 router.replace() 来手动导航,才能显示该新路由。例如:

const router = createRouter({
    
    
  history: createWebHistory(),
  routes: [{
    
     path: '/:articleName', component: Article }],
})

进入任何页面,/about,或者 /store ,最终都会呈现 Article 组件。如果我们在 /about 上添加一个新的路由:

router.addRoute({
    
     path: '/about', component: About })

页面仍然会显示 Article 组件,我们需要手动调用 router.replace() 来改变当前的位置,并覆盖我们原来的位置:

router.addRoute({
    
     path: '/about', component: About })
// 我们也可以使用 this.$route 或 route = useRoute() (在 setup 中)
router.replace(router.currentRoute.value.fullPath)

猜你喜欢

转载自blog.csdn.net/XiugongHao/article/details/132304980