3、嵌套路由

介绍

学习vue-router的一些学习笔记,所有笔记内容请看 vue-router学习笔记

嵌套路由

即路由中嵌套着路由

{
    path:'/user/:id',component:User
}

如下图所示:
/user/foo/ 路径对应着User模块,/user./foo/profile对应这User模块中的Profile模块
在这里插入图片描述
嵌套路由具体实现,在如下代码中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>weakMap</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="/user/foo">/user/foo</router-link>
    <router-link to="/user/foo/profile">/user/foo/profile</router-link>
    <router-link to="/user/foo/posts">/user/foo/posts</router-link>
  </p>
  
  // 此处的router-view代表着最顶层出口,渲染最高级路由匹配到的组件
  // 即User组件会被在此处渲染
  <router-view></router-view>
</div>
<script>

// 被渲染的组件中也可以包含自己的嵌套<router-view>
// 
  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>' }

// 在嵌套的路由中渲染组件,需要在VueRouter中使用children声明嵌套路由
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        // UserHome会被渲染在User中的<router-view>,当/user/:id被匹配成功时
        // 例如/user/:id/foo,就会将UserHome渲染在User中的<router-view>
        { path: '', component: UserHome },
				
        // UserProfile会被渲染在User组件中的<router-view>中
        // 当/user/:id/profile被匹配到时
        { path: 'profile', component: UserProfile },

        // UserPosts组件会被渲染在User组件中的<router-view>中
        // 当 /user/:id/posts 被匹配到时
        { path: 'posts', component: UserPosts }
      ]
    }
  ]
})

const app = new Vue({ 
    el:"#app",
    router
 })

</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值