5、Vue 3 - Vue Router 使用实录 : 嵌套路由的配置使用
一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构,例如:
/user/johnny/profile /user/johnny/posts
+------------------+ +-----------------+
| User | | User |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
通过 Vue Router,你可以使用嵌套路由配置来表达这种关系。
1、添加组件
src/views/ContactView.vue
<template>
<div class="container bg-primary">
<h3>联系我</h3>
</div>
</template>
src/views/CategoryView.vue
<template>
<div class="container bg-primary">
<h3>分类</h3>
</div>
</template>
2、修改 app 组件
src/views/HomeView.vue
<template>
<div class="container bg-primary p-5 text-white">首页</div>
<div class="bg-success py-5">
<p class="text-center text-white">嵌套路由</p>
<!--渲染嵌套路由-->
<router-view></router-view>
</div>
</template>
3、配置嵌套路由
src/router/index.ts
import { createRouter, createWebHistory } from "vue-router"
const router = createRouter({
history: createWebHistory(),
routes:[
...
{
path:'/home',
name:'home',
component: () => import('@/views/HomeView.vue'),
meta:{
'title':'首页',
},
// 配置嵌套路由
children:[
{
path:'/home/contact',
name:'联系我',
component: () => import('@/views/ContactView.vue')
},
{
path:'/home/category',
name:'分类',
component: () => import('@/views/CategoryView.vue')
}
]
},
...
]
})
export default router
4、使用测试
先访问首页 http://localhost:5173/home/
再访问嵌套路由看看:http://localhost:5173/home/contact
和 http://localhost:5173/home/category
请登录后再评论