深入Vue-Router路由嵌套理解

背景

創(chuàng)新互聯(lián)專注于龍巖網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供龍巖營銷型網(wǎng)站建設(shè),龍巖網(wǎng)站制作、龍巖網(wǎng)頁設(shè)計、龍巖網(wǎng)站官網(wǎng)定制、微信小程序服務(wù),打造龍巖網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供龍巖網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

最近有個初學Vue的朋友問我,為什么我的兩層路由跳不起來了,直接輸url也不行?信息不是很充足及看不到源碼的我,當時是那個一臉懵逼啊,心想這肯定是代碼的問題,跟層級無關(guān)。接著我繼續(xù)追問...(省略)...大致明白了情況,原來這位朋友沒有理解Vue-Router嵌套的原理,下面整理了一下我對Vue-Router路由嵌套的理解

Vue-Router嵌套路由

首先假設(shè)項目中有兩個路由Profile和Posts,按寫法把他們定義為一層路由,是Root的子路由,因此Root中要有router-view組件去承載子路由,才能實現(xiàn)子路由切換展示

一層路由

Root容器

 <div>
  <h2>Root</h2>
  <!-- 承載子路由的容器 -->
  <router-view />
 </div>

一層路由寫法

[
 {
  path: '/profile'
  component: profile // 組件引用 此處省略引用
 },
 {
  path: '/posts'
  component: posts // 組件引用 此處省略引用
 },
]

一層路由展示

Root的子路由展示是在Root中的,切換路由其實只是切換了router-view容器的內(nèi)容

/profile               /posts
+------------------+         +-----------------+
| Root       |         | Root      |
| +--------------+ |         | +-------------+ |
| | Profile   | | +------------> | | Posts    | |
| |       | |         | |       | |
| +--------------+ |         | +-------------+ |
+------------------+         +-----------------+

二層路由

在上面的基礎(chǔ)上,對profile加一層路由

profile容器

 <div>
  <h2>profile</h2>
  <!-- 承載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é)

任何子路由都是在其父路由的組件中切換顯示,不管是多少層的路由嵌套,都是這樣的理解,所以父路由需要有以下兩點,二者缺一不可

  • 有組件引用
  • 組件中有router-view組件

而我那個朋友就是父路由沒有引用組件,導致子路由沒有承載容器,自然而然就出現(xiàn)了他說的不起效的情況,這里把經(jīng)驗分享給大家,希望能對初學者有幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當前文章:深入Vue-Router路由嵌套理解
轉(zhuǎn)載注明:http://muchs.cn/article30/jepsso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、關(guān)鍵詞優(yōu)化App設(shè)計、標簽優(yōu)化、網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站