动态路由

知识点

动态路由是指在URL路径中含有动态参数的路由,比如说:/player/1, /player/2, /player/3等等。

  • 动态路由的匹配设置

实战演习

定制玩家的动态路径:/player/:id

  • Player.vue
  • router/index.js
  • App.vue

Player.vue

  1. <template>
  2. <div>
  3. <h1>球员页面</h1>
  4. <p>{{ detail }}</p>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: "Player",
  10. data() {
  11. return {
  12. detail: {}
  13. };
  14. },
  15. mounted() {
  16. // 接受url参数id
  17. this.detail = this.getPlayer(this.$route.params.uid);
  18. },
  19. /*
  20. beforeRouteUpdate(to, from, next) {
  21. this.detail = this.getPlayer(to.params.uid);
  22. next();
  23. },
  24. */
  25. methods: {
  26. getPlayer(uid) {
  27. switch (uid) {
  28. case '1':
  29. return {uid: 1,name: '库里',point: 26};
  30. case '2':
  31. return {uid: 2,name: '哈登',point: 30};
  32. default:
  33. return {uid: -1};
  34. }
  35. }
  36. }
  37. };
  38. </script>

router/index.js

  1. ...
  2. import Player from '@/components/Player'
  3. ...
  4. export default new Router({
  5. routes: [
  6. {
  7. path: '/player/:uid',
  8. name: 'Player',
  9. component: Player
  10. }
  11. ]
  12. })

App.vue

  1. <template>
  2. <div id="app">
  3. <p>
  4. <router-link to="/">Home</router-link>
  5. <router-link to="/player/1">库里</router-link>
  6. <router-link to="/player/2">哈登</router-link>
  7. </p>
  8. <router-view/>
  9. </div>
  10. </template>

课程文件

https://gitee.com/komavideo/LearnVueJS2

小马视频频道

http://komavideo.com