App.vue

因为二级路由在一级路由里,所以子组件组件都放在home文件里,即是src/pages/home文件夹中创建二级导航的组件classic.vue和Hot.vue

  1. const routes = [
  2. {
  3. path: "/",
  4. redirect: "/home_1",
  5. },
  6. {
  7. path: "/home_1",
  8. component: () =>
  9. import(/*webpackChunkName:"home"*/ "../pages/home/index.vue"),
  10. name: "home",
  11. alias: "/family",
  12. -----------------------------------------------------------------------------------------
  13. // 子路由重定向
  14. redirect:'/home_1/f-hot', // 不是写在子路由中!!!!
  15. // 用于实现子路由表
  16. children: [
  17. {
  18. path: "f-hot", // 子路由的path不用加/ 会自动加
  19. component: () =>
  20. import(/*webpackChunkName:home*/ "../pages/home/Hot.vue"),
  21. name:'f-hot_1'
  22. },
  23. {
  24. path: "classic", // 子路由的path不用加/ 会自动加
  25. component: () =>
  26. import(/*webpackChunkName:home*/ "../pages/home/classic.vue"),
  27. name:'classic_1'
  28. },
  29. ],
  30. },
  31. -----------------------------------------------------------------------------------------
  32. {
  33. path: "/about",
  34. component: () =>
  35. import(/*webpackChunkName:'about'*/ "../pages/about/index.vue"),
  36. name: "about",
  37. },

scr/pages/home/index.vue

  1. <template>
  2. <div>
  3. home组件
  4. <hr />
  5. <!-- 导航区域 -->
  6. <ul class="home-nav-list">
  7. <li>
  8. <router-link active-class="active" to="/home_1/f-hot">热映</router-link>
  9. </li>
  10. <li>
  11. <router-link active-class="active" to="/home_1/classic">经典电影</router-link>
  12. </li>
  13. </ul>
  14. <!-- 子路由展示区 -->
  15. <div>
  16. <router-view></router-view>
  17. </div>
  18. </div>
  19. </template>
  20. <style lang="stylus" scoped>
  21. .home-nav-list
  22. display flex
  23. width 200px
  24. justify-content space-evenly
  25. .active
  26. background blue
  27. color white
  28. </style>

命名路由

除了 path 以外,你还可以为任何路由提供 name 。这有以下优点:

  • 没有硬编码的URL
  • params 的自动编码/解码
  • 防止你在url中出现打字错误
  • 绕过路径排序(如显示一个)

我们将上面的案例进行优化

  1. children: [
  2. {
  3. path: "f-hot",
  4. component: () =>
  5. import(/*webpackChunkName:home*/ "../pages/home/Hot.vue"),
  6. name:'f-hot_1' // 添加name属性
  7. },
  8. {
  9. path: "classic",
  10. component: () =>
  11. import(/*webpackChunkName:home*/ "../pages/home/classic.vue"),
  12. name:'classic_1' // 添加name属性
  13. },
  14. ],

要链接到一个命名的路由,可以向 router-link 组件的 to 属性传递一个对象

  1. <!-- :to={name:'命名路由的名字'} -->
  2. <router-link :to="{name:'f-hot_1'}">热映</router-link>
  3. <router-link :to="{name:'classic_1'}">经典电影</router-link>