vue嵌套路由

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

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
  },
  //...其他子路由
  ]
  }
 ]
})

以下是一个例子:

  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>HelloWorldtitle>  
    <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="/user/foo">Userrouter-link>
      <router-link to="/user/foo/profile">UserHomerouter-link>
      <router-link to="/user/foo/posts">postsrouter-link>
    p>
    
    
    <router-view>router-view>
  div>
<script> 
const User = {
  template: `
    
class="user"> <h2>User {{ $route.params.id }}</h2> router-view> div> ` } const UserHome = { template: '<div>Homediv>' } const UserProfile = { template: '<div>Profilediv>' } const UserPosts = { template: '<div>Postsdiv>' } 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(…)。

你可能感兴趣的:(vue,vue)