一、概念

动态路由。指的是路由的 path 中有一部分内容是动态不固定的。
例如,我们要跳转到“修改学生”的页面,那么我们的路由可以设置成以下形式:

  1. /home/studentsUpdate/001

其中,001 的部分就是路由中动态的部分。

二、动态路由的跳转

动态路由的跳转方式和普通路由没有区别,只是在跳转的路径中需要通过 / 分割加上动态的内容:

  1. <router-link to="/home/studentsUpdate/001"></router-link>
  1. this.$router.push("/home/studentsUpdate/001");

但是在实际应用中,大部分时候路由的动态内容都不是一个写死的字符串,而是一个变量名。因此在跳转动态路由时,可能会涉及到字符串的拼接:

  1. <router-link :to="'/home/studentsUpdate/' + studentsId"></router-link>
  2. <router-link :to="`/home/studentsUpdate/${studentsId}`"></router-link>
  3. <router-link :to="{ path: '/home/studentsUpdate/' + studentsId}"></router-link>
  1. this.$router.push("/home/studentsUpdate/" + studentsId);

三、动态路由的配置

在路由配置时,动态路由和普通路由的配置方式有一些区别。
由于动态路由的路径中有一部分内容是动态的,因此在配置路由的 path 时,需要通过 :变量名 的方式来匹配路由中的动态内容。

  1. const routes = [
  2. {
  3. path: '/home',
  4. component: Home,
  5. children: [
  6. {
  7. path: 'studentsUpdate/:studentsId',
  8. name: 'StudentsUpdate',
  9. component: StudentsUpdate
  10. }
  11. ]
  12. }
  13. ]

上例中的 studentsId 可任意命名。

四、获取动态路由参数

动态路由中的动态数据,可以作为参数来实现路由之间的传参。
例如我们前面的例子中,在跳转到“修改学生”的路由中,携带了当前学生的 id。因此,我们可以在修改学生的组件中获取动态路由中的学生 id 参数。
Vue Router 中获取动态路由参数的方式主要有两种:

  • 通过路由对象获取
  • 通过 Prop 获取

    1、通过路由对象获取

    可以在组件中通过路由对象 $route 来获取动态路由的参数:
    1. <template>
    2. <h1>{{$route.params.studentsId}}</h1>
    3. </template>
    4. <script>
    5. export default {
    6. mounted() {
    7. console.log(this.$route.params.studentsId)
    8. }
    9. }
    10. </script>
    可以在 <template> 中直接通过 $route.params 直接渲染,也可以在生命周期函数中通过 this.$route.params 访问使用。
    注:studentsId 是我们在配置动态路由时设置的变量名。

    2、通过 Prop 获取

    还可以在组件中通过 Prop 来获取动态路由的参数。
    首先,需要在动态路由配置时添加一个 props: true 属性:
    1. const routes = [
    2. {
    3. path: '/home',
    4. component: Home,
    5. children: [
    6. {
    7. path: 'studentsUpdate/:studentsId',
    8. name: 'StudentsUpdate',
    9. props: true,
    10. component: StudentsUpdate
    11. }
    12. ]
    13. }
    14. ]
    然后,就可以在组件中通过 Prop 来接收参数:
    1. export default {
    2. props: ['studentsId']
    3. }
    后续在组件中就当作普通的 Prop 值进行使用即可。