嵌套路由
image.png
為什么要配置子路由?
子路由相當于子菜單。子路由的情況一般用在一個頁面有他的基礎模版,然后它下面的頁面都隸屬于這個模版,只是部分改變樣式。
改造App.vue的導航代碼
我們需要先改造app.vue的導航代碼,來實現基本的導航功能。我們用<router-link>標簽增加了兩個新的導航鏈接。
<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>
改寫components/Hi.vue頁面
<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
<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>
<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字段。
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},
]
}
]
})