嵌套路由的使用
从文档中可知,嵌套路由的使用场景为,可以根据提供的URL来访问对应层级的组件,并将子组件的内容,渲染至上一级的< router-view >中
文档给出的图示:
/user/foo/profile /user/foo/posts
+------------------+ +-----------------+
| User | | User |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
嵌套路由的构建
我们知道,创建一个路由配置需要path和component两个字段
const User = {
template: "<div>this is a user</div>"
}
const router = new VueRouter({
routes:[
{
// 路由访问路径
path: "/user/foo",
// 路径访问的组件
component: User
}
]
})
那么嵌套路由呢? 我们需要这是需要一个新的字段children,这是一个数组数组,里面包含的,就是我们下一层级访问的路由对象
const router = new VueRouter({
routes:[
{
// 路由访问路径
path: "/user/foo",
// 路径访问的组件
component: User,
children: [
{
path: "profile",
component: Profile
}
]
}
]
})
这样,我们就可以通过/user/foo/profile 这个路径,来访问Profile组件,并将其渲染在父级组件的router-view中,这个嵌套关系可以一直持续下去,路径多写层,小问题
嵌套路由的动态匹配
在文档提及动态路由匹配的时候,举出了一个例子
模式 | 匹配路径 | URL传参($route.params) |
---|---|---|
/user/:username | /user/evan | { username: ‘evan’ } |
例子说明,URL中存在/:xxx格式的子路径,那么在路由中就会自动匹配成/xxx这样的子路径,同时,router会将参数格式化成一个对象 ,可使用this.$route.params访问该对象,若路径中无参数,则该对象为{}
我们知道单层路由可以通过这样的动态参数进行匹配,那么嵌套路由可以吗?
我们先修改一下路由的配置
<!-- 我们定义id为customid -->
<router-link to="/user/customid/profile">Profile</router-link>
const User = {
template:
`
<div>
<h2>User {{$route.params.id}}</h2>
<router-view></router-view>
</div>
`
}
const Profile = {
template: "<div>Profile {{$route.params.id}}</div>"
}
const router = new VueRouter({
routes: [
{
path: "/user/:id",
component: User,
children: [
{
path: "profile",
component: Profile
}
]
}
]
})
这是,浏览器打开html文件,会显示
router-link转换后的a标签,以及路由访问到的组件都已经被渲染
完整代码
<html>
<header>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</header>
<body>
<div id="app">
<router-link to="/user/customid/profile">Profile</router-link>
<router-view></router-view>
</div>
<script>
const User = {
template:
`
<div>
<h2>User {{$route.params.id}}</h2>
<router-view></router-view>
</div>
`
}
const Profile = {
template: "<div>Profile {{$route.params.id}}</div>"
}
const router = new VueRouter({
routes: [
{
path: "/user/:id",
component: User,
children: [
{
path: "profile",
component: Profile
}
]
}
]
})
new Vue({ router }).$mount('#app')
</script>
</body>
</html>