DAY25 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (中)

接續上一篇 Vue Router 的筆記,這篇主要是來講解巢狀路由。
何謂巢狀路由?

巢狀路由

先看一下這張圖

結構如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const routers = [
{
path: '/link1'
component: Link1,
children:[
{
path: 'profile'
component: PROFILE
}
]
},
{
path: '/link2'
component: Link2,
children:[
{
path: 'post'
component: POST
}
]
},
{
path: '/link3'
component: Link3,
children:[
{
path: 'news'
component: NEWS
}
]
},
]

對我來說巢狀路由的狀態就是,當點了某個連結 <router-link></router-link><router-view></router-view> 就會導向某個模組 A ,在這個模組 A 裡也有一或多個 <router-link></router-link> ,而點選了模組 A 裡面的某個連結後,模組 A 裡面 <router-view></router-view> 就會導向模組 B。

命名路由

除了給予路由路徑及模組外,還可以命名(name)該路由,並且該路由也可以透過該名來跳轉。

不帶參數

1
2
3
4
5
6
7
const routers = [
{
path: '/home',
name: 'home',
component: HOME
}
]

將上面的路由用在連結上

1
<router-link :to="{ name: 'home'}"></router-link>

帶參數

1
2
3
4
5
6
7
const routers = [
{
path: '/user/:username',
name: 'user',
component: USER
}
]

將上面的路由用在連結上

1
<router-link :to="{ name: 'user', params: {username: 'Celeste'} }"></router-link>

命名視圖

想同時顯示多個模組的時候就可以利用此方法。

上圖的結構如下

沒有屬性 name<router-view></router-view> 即適用 default 所設定的模組。

另外同個路由下有多個模組需要顯示的話,一定要使用 components:{}

1
2
3
4
<!-- /user -->
<router-link to="/user"></router-link>
<router-view></router-view>
<router-view name="B"></router-view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const ComponentB = {
template: `<div>
<p>ComponentB</p>
<router-link to="/user/profile"></router-link>
<router-view></router-view>
<router-view name="d"></router-view>
</div>
`
}
const routers = [
{
path: '/user',
components: {
default: ComponentA,
B: ComponentB,
},
children:[
{
path: 'profile',
components:{
default: ComponentC,
d: ComponentD,
}
}
]
}
]

其他導向方法

除了上面所用的 <router-link :to="path"></router-link> 外,還可以透過 $router.push(location,onComplete?,onAbort?) 前往其他路由。

一定有很多人疑惑了 $router$route 有甚麼差別?
$router 係為得到路由實例,而 $route 係為得到路由對象屬性。

push() 方法在 $router 裡的原型鏈(__proto__)上。

push方法

1
2
3
4
5
//直接前往該位址
this.$router.push('/user')

//帶參數
this.$router.push({ path: '/user', params: {username: 'Celeste'}, query: { search: 'like'}})

replace方法

會替代目前 history 中的紀錄。

1
this.$router.replace('/user')

go方法

在瀏覽器紀錄中,往前或往後移動。

1
2
3
// n 為正 → 瀏覽器紀錄中往前 n 步
// n 為負 → 瀏覽器紀錄中往後 n 步
this.$router.go(n)

See the Pen DAY25 | 跟 Vue.js 認識的30天 - Vue 套餐之路由器 Vue Router (中) by Celeste6666 (@celeste6666) on CodePen.

參考資料

Vue Router - 命名路由

Vue Router - 命名视图

Vue Router - 编程式的导航