[2]vue-router配置子路由

資料來源于技術胖的個人網站

嵌套路由

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},
      ]
    }
  ]
})
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。