vue嵌套路由

1.存在的原因
更简单地表达多层嵌套地组件之间的关系。一个被渲染的组件同样可以包含<router-view>

const User={
    template:`
    <div class="user">
        <h2>user {{ $route.params.id }}</h2>
        <router-view></router-view>//嵌套的出口
    </div>
    `
}

要在嵌套的出口中渲染组件,必须在VueRouter的参数中使用children配置,children的配置和routes是一致的。所以可以嵌套多层路由。

const router=new VueRouter({
    routes:[
        { path:'/user/:id',component:User,
          children:[
            { path:'profile',component:UserProfile },
            { path:'posts',component:UserPosts }
          ]
        }
    ]
})

如果子组件当中没有提供一个空的子路由,那么当子路由的路径不存在时,路由出口不会渲染任何的东西。基于上面的配置,当访问/user/foo时,路由出口没有渲染出东西。

const router=new VueRouter({
 routes:[
  {
  path:'/user/:id',component:User,
  children:[
  {
  path:'',component:UserHome
  },
  //...其他子路由
  ]
  }
 ]
})

以下是一个例子:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>HelloWorld</title>  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>    
<body>  
  <div id="app">
    <p>
      <!-- 使用 router-link 组件来导航. -->
      <!-- 通过传入 `to` 属性指定链接. -->
      <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
      <router-link to="/user/foo">User</router-link>
      <router-link to="/user/foo/profile">UserHome</router-link>
      <router-link to="/user/foo/posts">posts</router-link>
    </p>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
  </div>
<script> 
const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

const UserHome = { template: '<div>Home</div>' }
const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        // UserHome will be rendered inside User's <router-view>
        // when /user/:id is matched
        { path: '', component: UserHome },

        // UserProfile will be rendered inside User's <router-view>
        // when /user/:id/profile is matched
        { path: 'profile', component: UserProfile },

        // UserPosts will be rendered inside User's <router-view>
        // when /user/:id/posts is matched
        { path: 'posts', component: UserPosts }
      ]
    }
  ]
})

const app = new Vue({ router }).$mount('#app')
</script>  

</body>  
</html>  

最后,点击 等同于调用 router.push(…)。

猜你喜欢

转载自blog.csdn.net/e_li_na/article/details/80182681