介绍
学习vue-router的一些学习笔记,所有笔记内容请看 vue-router学习笔记
嵌套路由
即路由中嵌套着路由
{
path:'/user/:id',component:User
}
如下图所示:
/user/foo/ 路径对应着User模块,/user./foo/profile对应这User模块中的Profile模块
嵌套路由具体实现,在如下代码中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>weakMap</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link>
<router-link to="/user/foo/profile">/user/foo/profile</router-link>
<router-link to="/user/foo/posts">/user/foo/posts</router-link>
</p>
// 此处的router-view代表着最顶层出口,渲染最高级路由匹配到的组件
// 即User组件会被在此处渲染
<router-view></router-view>
</div>
<script>
// 被渲染的组件中也可以包含自己的嵌套<router-view>
//
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}
const UserHome = { template: '<div>Home</div>' }
const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }
// 在嵌套的路由中渲染组件,需要在VueRouter中使用children声明嵌套路由
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
// UserHome会被渲染在User中的<router-view>,当/user/:id被匹配成功时
// 例如/user/:id/foo,就会将UserHome渲染在User中的<router-view>
{ path: '', component: UserHome },
// UserProfile会被渲染在User组件中的<router-view>中
// 当/user/:id/profile被匹配到时
{ path: 'profile', component: UserProfile },
// UserPosts组件会被渲染在User组件中的<router-view>中
// 当 /user/:id/posts 被匹配到时
{ path: 'posts', component: UserPosts }
]
}
]
})
const app = new Vue({
el:"#app",
router
})
</script>
</body>
</html>