一、概念
动态路由。指的是路由的 path 中有一部分内容是动态不固定的。
例如,我们要跳转到“修改学生”的页面,那么我们的路由可以设置成以下形式:
/home/studentsUpdate/001
二、动态路由的跳转
动态路由的跳转方式和普通路由没有区别,只是在跳转的路径中需要通过 / 分割加上动态的内容:
<router-link to="/home/studentsUpdate/001"></router-link>
this.$router.push("/home/studentsUpdate/001");
但是在实际应用中,大部分时候路由的动态内容都不是一个写死的字符串,而是一个变量名。因此在跳转动态路由时,可能会涉及到字符串的拼接:
<router-link :to="'/home/studentsUpdate/' + studentsId"></router-link><router-link :to="`/home/studentsUpdate/${studentsId}`"></router-link><router-link :to="{ path: '/home/studentsUpdate/' + studentsId}"></router-link>
this.$router.push("/home/studentsUpdate/" + studentsId);
三、动态路由的配置
在路由配置时,动态路由和普通路由的配置方式有一些区别。
由于动态路由的路径中有一部分内容是动态的,因此在配置路由的 path 时,需要通过 :变量名 的方式来匹配路由中的动态内容。
const routes = [{path: '/home',component: Home,children: [{path: 'studentsUpdate/:studentsId',name: 'StudentsUpdate',component: StudentsUpdate}]}]
四、获取动态路由参数
动态路由中的动态数据,可以作为参数来实现路由之间的传参。
例如我们前面的例子中,在跳转到“修改学生”的路由中,携带了当前学生的 id。因此,我们可以在修改学生的组件中获取动态路由中的学生 id 参数。
Vue Router 中获取动态路由参数的方式主要有两种:
- 通过路由对象获取
- 通过 Prop 获取
1、通过路由对象获取
可以在组件中通过路由对象$route来获取动态路由的参数:
可以在<template><h1>{{$route.params.studentsId}}</h1></template><script>export default {mounted() {console.log(this.$route.params.studentsId)}}</script>
<template>中直接通过$route.params直接渲染,也可以在生命周期函数中通过 this.$route.params 访问使用。
注:studentsId 是我们在配置动态路由时设置的变量名。2、通过 Prop 获取
还可以在组件中通过 Prop 来获取动态路由的参数。
首先,需要在动态路由配置时添加一个props: true属性:
然后,就可以在组件中通过 Prop 来接收参数:const routes = [{path: '/home',component: Home,children: [{path: 'studentsUpdate/:studentsId',name: 'StudentsUpdate',props: true,component: StudentsUpdate}]}]
后续在组件中就当作普通的 Prop 值进行使用即可。export default {props: ['studentsId']}
