1. 程式人生 > 其它 >Vue 對巢狀路由的理解

Vue 對巢狀路由的理解

之前使用巢狀路由的時候發現搞不清楚為什麼沒有正確顯示,查閱文件後,根據自己的理解把實驗過程記錄一下

<!-- HTML -->
<div id="app">
  <p>
    <router-link to="/a">a</router-link>
    **
    <router-link to="/a/b">b</router-link>
    **
    <router-link to="/a/b/c">c</router-link>
  </p>
  <router-view></router-view>
</div>

  

/* CSS */
#app>p{
    border:5px solid red;
}
.a{
    border:5px solid green;
}
.b{
    border:5px solid yellow;
}
.c{
    border:5px solid blue;
}

  

// JavaScript
const User = {
  template: `
    <div class="user">
      <h2>顯示區</h2>
      <router-view></router-view>
    </div>
  `
}

const a = { template: '<div class="a"><p>a路由</p><router-view></router-view></div>' }
const b = { template: '<div class="b"><p>b路由</p><router-view></router-view></div>' }
const c = { template: '<div class="c"><p>c路由</p><router-view></router-view></div>' }

const router = new VueRouter({
  routes: [
    { path: '/', component: User,
      children: [
        {   name:'a',
            path: 'a', 
            component: a,
            children:[
              {   name:'b',
                  path: 'b', 
                component: b,
                children:[
                 { 
                    name: 'c',
                    path: 'c',
                    component: c }   
                ]
                 },  
            ]
         },		
      ]
    }
  ]
})

const app = new Vue({ router }).$mount('#app')

  

結論:巢狀路由就是匹配路由表的路徑,把元件切換出來,切換元件內也必須有router-view,這樣才能顯示其中的子路由