1. 程式人生 > >三十三、vue-router配置子路由

三十三、vue-router配置子路由

                             vue-router配置子路由

      子路由的情況一般用在一個頁面有他的基礎模版,然後它下面的頁面都隸屬於這個模版,只是部分改變樣式。我們接著第一節課的例項,在Hi頁面的下面新建兩個子頁面,分別是 “Hi頁面1” 和 “Hi頁面2”,來實現子路由。

1、 App.vue程式碼

      我們需要先改造app.vue的導航程式碼,來實現基本的導航功能。我們用標籤增加了兩個新的導航連結。

    <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>

2、改寫components/Hi.vue頁面

      把Hi.vue改成一個通用的模板,加入<router-view>標籤,給子模板提供插入位置。“Hi頁面1” 和 “Hi頁面2” 都相當於“Hi頁面”的子頁面,有點想繼承關係。我們在“Hi頁面”里加入<router-view>標籤。

<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>

3、、在components目錄下新建兩個元件模板 Hi1.vue 和 Hi2.vue

      新建的模板和Hi.vue沒有太多的差別,知識改變了data中message的值,也就是輸出的結果不太一樣了。
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>

Hi2.vue

<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>

4、修改router/index.js程式碼

      children欄位後邊跟的是個陣列,數組裡和其他配置路由基本相同,需要配置path和component。具體看一下這個子路由的配置寫法。

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},
      ]
    }
  ]
})