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,这样才能显示其中的子路由

 

posted @ 2021-12-23 10:34  时间观测者  阅读(58)  评论(0编辑  收藏  举报