嵌套路由~
### 作业
- App.vue
```vue
<script setup></script>
<template>
<router-link to="/home">首页</router-link>
<router-link to="/profile">个人资料</router-link>
<router-link to="/posts">文章</router-link>
<RouterView></RouterView>
</template>
```
- router.js
```js
const routes = [
{path: '/',redirect: '/home'},
{path: '/home',name: 'Home',component: Home},
{path: '/profile',name: 'Profile',component: Profile},
];
export const router = createRouter({
history: createWebHistory(),
routes
});
```
```vue
<script setup></script>
<template>
<h2>User{{ $route.params.id }}</h2>
<!-- 要写出口,子文件 -->
<RouterView></RouterView>
</template>
```
### 笔记
* 在 User 组件的模板中添加 `<router-view></router-view>`,用于渲染匹配的子组件
1. **空路径的嵌套路由**
```js
{
path: '/user/:id',
component: User,
children: [
{ path: '', component: UserHome },
{ path: 'profile', component: UserProfile }
]
}
```
2. **命名路由的嵌套**:添加 name 属性:
```js
{
path: '/user/:id',
component: User,
children: [
{ path: '', name: 'user-home', component: UserHome },
{ path: 'profile', name: 'user-profile', component: UserProfile },
{ path: 'posts', name: 'user-posts', component: UserPosts }
]
}
```
* 这样可以通过名称进行导航,例如使用 `this.$router.push({ name: 'user-profile', params: { id: userId }})`。