深入深入Vue-Router路由嵌套理解路由嵌套理解
背景背景
最近有个初学Vue的朋友问我,为什么我的两层路由跳不起来了,直接输url也不行?信息不是很充足及看不到源码的我,当时
是那个一脸懵逼啊,心想这肯定是代码的问题,跟层级无关。接着我继续追问…(省略)…大致明白了情况,原来这位朋友没有
理解Vue-Router嵌套的原理,下面整理了一下我对Vue-Router路由嵌套的理解
Vue-Router嵌套路由嵌套路由
首先假设项目中有两个路由Profile和Posts,按写法把他们定义为一层路由,是Root的子路由,因此Root中要有router-view组
件去承载子路由,才能实现子路由切换展示
一层路由一层路由
Root容器
<div>
<h1>Root</h1>
<!-- 承载子路由的容器 -->
<router-view />
</div>
一层路由写法
[
{
path: '/profile'
component: profile // 组件引用 此处省略引用
},
{
path: '/posts'
component: posts // 组件引用 此处省略引用
},
]
一层路由展示
Root的子路由展示是在Root中的,切换路由其实只是切换了router-view容器的内容
/profile /posts
+------------------+ +-----------------+
| Root | | Root |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
二层路由二层路由
在上面的基础上,对profile加一层路由
profile容器
<div>
<h1>profile</h1>
<!-- 承载profile子路由的容器 -->
<router-view />
</div>
profile子路由
[
{
path: '/profile'
component: profile, // 此处不能少
children: [
{
path: '/profile/list',
component: profileList
},
评论10