http://jspang.com/2017/04/13/vue-router/ 原文網址
我們上節課初步了解Vue-router的初步知識,也學會了基本的跳轉,那我們這節課學習一下子菜單的路由方式,也叫子路由。子路由的情況一般用在一個頁面有他的基礎模版,然后它下面的頁面都隸屬於這個模版,只是部分改變樣式。我們接着第一節課的實例,在Hi頁面的下面新建兩個子頁面,分別是 “Hi頁面1” 和 “Hi頁面2”,來實現子路由。
一、改造App.vue的導航代碼
我們需要先改造app.vue的導航代碼,來實現基本的導航功能。我們用<router-link>標簽增加了兩個新的導航鏈接。
App.vue代碼
1
2
3
4
5
6
|
<p>導航 :
<router-link to="/">首頁</router-link> |
<router-link to="/hi">Hi頁面</router-link> |
<router-link to="/hi/hi1">-Hi頁面1</router-link> |
<router-link to="/hi/hi2">-Hi頁面2</router-link>
</p>
|
這時候我們再訪問主頁的時候導航欄就發生了變化。多出了兩個自導航:Hi頁面1 和 Hi頁面2
二、改寫components/Hi.vue頁面
把Hi.vue改成一個通用的模板,加入<router-view>標簽,給子模板提供插入位置。“Hi頁面1” 和 “Hi頁面2” 都相當於“Hi頁面”的子頁面,有點想繼承關系。我們在“Hi頁面”里加入<router-view>標簽。
components/Hi.vue,就是第5行的代碼,其他代碼不變。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<router-view class="aaa"></router-view>
</div>
</template>
<script>
export default {
name: 'hi',
data () {
return {
msg: 'Hi, I am JSPang'
}
}
}
</script>
<style scoped>
</style>
|
三、在components目錄下新建兩個組件模板 Hi1.vue 和 Hi2.vue
新建的模板和Hi.vue沒有太多的差別,知識改變了data中message的值,也就是輸出的結果不太一樣了。
Hi1.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'hi',
data () {
return {
msg: 'Hi, I am Hi1!'
}
}
}
</script>
<style scoped>
</style>
|
Hi2.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'hi',
data () {
return {
msg: 'Hi, I am Hi2'
}
}
}
</script>
<style scoped>
</style>
|
四、修改router/index.js代碼
我們現在導航有了,母模板和子模板也有了,只要改變我們的路由配置文件就可以了。子路由的寫法是在原有的路由配置下加入children字段。
1
2
3
4
|
children:[
{path:'/',component:xxx},
{path:'xx',component:xxx},
]
|
children字段后邊跟的是個數組,數組里和其他配置路由基本相同,需要配置path和component。具體看一下這個子路由的配置寫法。
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
|
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Hi from '@/components/Hi'
import Hi1 from '@/components/Hi1'
import Hi2 from '@/components/Hi2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},{
path:'/hi',
component:Hi,
children:[
{path:'/',component:Hi},
{path:'hi1',component:Hi1},
{path:'hi2',component:Hi2},
]
}
]
})
|
需要注意的是,在配置路由文件前,需要先用import引入Hi1和Hi2。
總結:
這節課學的內容在路由配置里經常用到,比如我們作一個購物模塊,購物模塊里有很多相同的元素,我們就會利用這種子路由的形式,先定一個父頁面,然后再修改子頁面。希望這節課對你有幫助,其實子路由的步驟還是有些繁瑣的,所以希望你們多練習幾遍,能夠完全掌握。