嵌套路由

知识点

嵌套路由是指在动态路由的基础上再加上附加的嵌套URL(即:组件),比如说:(/player/:uid/*)/player/1/profile, /player/1/stats等。

  • 嵌套路由的使用方法

实战演习

  • Player/Profile.vue
  • Player/Stats.vue
  • router/index.js
  • Player.vue

Player/Profile.vue

  1. <template>
  2. <div>
  3. <h2>球员简介:{{$route.params.uid}}</h2>
  4. </div>
  5. </template>

Player/Stats.vue

  1. <template>
  2. <div>
  3. <h2>球员数据:{{$route.params.uid}}</h2>
  4. </div>
  5. </template>

router/index.js

  1. import PlayerProfile from '@/components/Player/Profile'
  2. import PlayerStats from '@/components/Player/Stats'
  3. ...
  4. {
  5. path: '/player/:uid',
  6. name: 'Player',
  7. component: Player,
  8. children: [
  9. {
  10. path: 'profile',
  11. component: PlayerProfile
  12. },
  13. {
  14. path: 'stats',
  15. component: PlayerStats
  16. },
  17. ]
  18. }

Player.vue

  1. <template>
  2. <div>
  3. <h1>球员页面</h1>
  4. <ul>
  5. <li>编号:{{detail.uid}}</li>
  6. <li>名字:{{detail.name}}</li>
  7. <li>得分:{{detail.point}}</li>
  8. </ul>
  9. <router-link :to="profile">简介</router-link>
  10. <router-link :to="stats">数据</router-link>
  11. <hr>
  12. <router-view></router-view>
  13. </div>
  14. </template>
  15. ...
  16. <script>
  17. ...
  18. data() {
  19. return {
  20. detail: {},
  21. profile: '',
  22. stats: '',
  23. };
  24. },
  25. mounted() {
  26. this.detail = this.getPlayer(this.$route.params.uid);
  27. this.profile = '/player/' + this.$route.params.uid + '/profile';
  28. this.stats = '/player/' + this.$route.params.uid + '/stats';
  29. },
  30. beforeRouteUpdate(to, from, next) {
  31. this.detail = this.getPlayer(to.params.uid);
  32. this.profile = '/player/' + to.params.uid + '/profile';
  33. this.stats = '/player/' + to.params.uid + '/stats';
  34. next();
  35. },
  36. ...
  37. </script>

课程文件

https://gitee.com/komavideo/LearnVueJS2

小马视频频道

http://komavideo.com