背景
最近有個(gè)初學(xué)Vue的朋友問(wèn)我,為什么我的兩層路由跳不起來(lái)了,直接輸url也不行挚歧?信息不是很充足及看不到源碼的我扛稽,當(dāng)時(shí)是那個(gè)一臉懵逼啊,心想這肯定是代碼的問(wèn)題滑负,跟層級(jí)無(wú)關(guān)在张。接著我繼續(xù)追問(wèn)...(省略)...大致明白了情況用含,原來(lái)這位朋友沒(méi)有理解Vue-Router嵌套的原理,下面整理了一下我對(duì)Vue-Router路由嵌套的理解
Vue-Router嵌套路由
首先假設(shè)項(xiàng)目中有兩個(gè)路由Profile和Posts帮匾,按寫法把他們定義為一層路由啄骇,是Root的子路由
,因此Root中要有router-view
組件去承載子路由瘟斜,才能實(shí)現(xiàn)子路由切換展示
一層路由
Root容器
<div>
<h1>Root</h1>
<!-- 承載子路由的容器 -->
<router-view />
</div>
一層路由寫法
[
{
path: '/profile'
component: profile // 組件引用 此處省略引用
},
{
path: '/posts'
component: posts // 組件引用 此處省略引用
},
]
一層路由展示
Root的子路由展示是在Root中的缸夹,切換路由其實(shí)只是切換了router-view
容器的內(nèi)容
/profile /posts
+------------------+ +-----------------+
| Root | | Root |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
二層路由
在上面的基礎(chǔ)上,對(duì)profile加一層路由
profile容器
<div>
<h1>profile</h1>
<!-- 承載profile子路由的容器 -->
<router-view />
</div>
profile子路由
[
{
path: '/profile'
component: profile, // 此處不能少
children: [
{
path: '/profile/list',
component: profileList
},
{
path: '/profile/item',
component: profileItem
}
]
},
...
]
二層路由展示
和一層路由相同的是螺句,Profile的子路由是在Profile容器中切換展示的虽惭,所以Profile路由的component是必不可少的
/profile/list /profile/item
+------------------+ +-----------------+
| Root | | Root |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Profile | |
| | +----------+ | | | | +---------+ | |
| | | list | | | | | | item | | |
| | | | | | | | | | | |
| | +----------+ | | | | +---------+ | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
路由嵌套總結(jié)
任何子路由都是在其父路由的組件中切換顯示,不管是多少層的路由嵌套蛇尚,都是這樣的理解芽唇,所以父路由需要有以下兩點(diǎn),二者缺一不可
有組件引用
組件中有router-view組件
而我那個(gè)朋友就是父路由沒(méi)有引用組件取劫,導(dǎo)致子路由沒(méi)有承載容器匆笤,自然而然就出現(xiàn)了他說(shuō)的不起效的情況,這里把經(jīng)驗(yàn)分享給大家谱邪,希望能對(duì)初學(xué)者有幫助