1. 程式人生 > 實用技巧 >VueRouter路由巢狀

VueRouter路由巢狀

配置巢狀路由

要配置巢狀路由,我們需要在配置的引數中使用 children 屬性:

  {
    path: '路由地址',
    component: '渲染元件',
    children: [
      {
        path: '路由地址',
        component: '渲染元件'
      }
    ]
  }

基本使用

接下來我們對上一小節的例子來做一個改造:在文章頁面,我們對文章進行分類,提供兩個連結按鈕 vue、react,點選可以跳轉到對應的文章列表,具體程式碼示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>
      //義了兩個跳轉連結。
      <router-link to="/index">首頁</router-link>
      <router-link to="/article">文章</router-link>
    </div>
    //使用 <router-view></router-view> 元件來渲染匹配元件。
    <router-view></router-view>
  </div>
</body>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script type="text/javascript">

//定義了元件 Index
const Index = Vue.component('index', {
  template: '<div>Hello,歡迎使用慕課網學習 Vue 教程!</div>',
})
//義了元件 Article,元件內部使用 <router-link></router-link> 定義來兩個跳轉連結,使用 <router-view></router-view> 來渲染匹配元件
const Article = Vue.component('myArticle', {
  template: `<div>
      <div>
        <router-link to="/article/vue">vue</router-link>
        <router-link to="/article/react">react</router-link>
      </div>
      <router-view></router-view>
    </div>`,
})
//定義了元件 VueArticle.
const VueArticle = Vue.component('vueArticle', {
  template: `<ul><li>1. Vue 基礎學習</li><li>2. Vue 專案實戰</li></ul>`,
})
//定義了元件 ReactArticle。
const ReactArticle = Vue.component('reactArticle', {
  template: `<ul><li>1. React 基礎學習</li><li>2. React 專案實戰</li></ul>`,
})
//定義了路由陣列,在 ‘/article’ 中配置來巢狀路由 children
const routes = [
  { path: '/index', component: Index },
  { 
    path: '/article', 
    component: Article ,
    children: [
      {
        path: 'vue', 
        component: VueArticle ,
      },
      {
        path: 'react', 
        component: ReactArticle ,
      }
    ]
  }
]
//建立 router 例項,然後傳 routes 配置。
const router = new VueRouter({
  routes: routes
})
//通過 router 配置引數注入路由
  var vm = new Vue({
    el: '#app',
    router,
    data() {
      return {}
    }
  })
</script>
</html>

定義路由地址

在上述的例子中,我們通過 ‘/article/vue’ 來訪問巢狀路由,但是有時候你可能不希望使用巢狀路徑,這時候我們可以對上面例子中的配置資訊做一點修改:

const routes = [
  { path: '/index', component: Index },
  { 
    path: '/article', 
    component: Article ,
    children: [
      {
        path: '/vueArticle', 
        component: VueArticle ,
      },
      {
        path: '/reactArticle', 
        component: ReactArticle ,
      }
    ]
  }
]

以 ‘/’ 開頭的巢狀路徑會被當作根路,因此,我們訪問 ‘/vueArticle’ 就相當於訪問之前的 ‘/article/vue’。