DAY25 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (中)
接續上一篇 Vue Router 的筆記,這篇主要是來講解巢狀路由。
何謂巢狀路由?
巢狀路由
先看一下這張圖
結構如下
1 | const routers = [ |
對我來說巢狀路由的狀態就是,當點了某個連結 <router-link></router-link>
, <router-view></router-view>
就會導向某個模組 A ,在這個模組 A 裡也有一或多個 <router-link></router-link>
,而點選了模組 A 裡面的某個連結後,模組 A 裡面 <router-view></router-view>
就會導向模組 B。
命名路由
除了給予路由路徑及模組外,還可以命名(name
)該路由,並且該路由也可以透過該名來跳轉。
不帶參數
1 | const routers = [ |
將上面的路由用在連結上
1 | <router-link :to="{ name: 'home'}"></router-link> |
帶參數
1 | const routers = [ |
將上面的路由用在連結上
1 | <router-link :to="{ name: 'user', params: {username: 'Celeste'} }"></router-link> |
命名視圖
想同時顯示多個模組的時候就可以利用此方法。
上圖的結構如下
沒有屬性 name
的 <router-view></router-view>
即適用 default
所設定的模組。
另外同個路由下有多個模組需要顯示的話,一定要使用 components:{}
。
1 | <!-- /user --> |
1 | const ComponentB = { |
其他導向方法
除了上面所用的 <router-link :to="path"></router-link>
外,還可以透過 $router.push(location,onComplete?,onAbort?)
前往其他路由。
一定有很多人疑惑了 $router
跟 $route
有甚麼差別?$router
係為得到路由實例,而 $route
係為得到路由對象屬性。
push()
方法在 $router
裡的原型鏈(__proto__
)上。
push
方法
1 | //直接前往該位址 |
replace
方法
會替代目前 history 中的紀錄。
1 | this.$router.replace('/user') |
go
方法
在瀏覽器紀錄中,往前或往後移動。
1 | // n 為正 → 瀏覽器紀錄中往前 n 步 |
See the Pen DAY25 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (中) by Celeste6666 (@celeste6666) on CodePen.
參考資料