推荐答案
在 Vue Router 中,传递路由参数主要有以下几种方式:
动态路由参数:通过在路由路径中使用
:param的形式定义动态路由参数,然后在组件中通过this.$route.params访问。// www.javascriptcn.com code example // 路由定义 const routes = [ { path: '/user/:id', component: User } ]; // 组件中访问 export default { mounted() { console.log(this.$route.params.id); } };查询参数:通过在路由路径中使用
?key=value的形式传递查询参数,然后在组件中通过this.$route.query访问。// www.javascriptcn.com code example // 路由跳转 this.$router.push({ path: '/user', query: { id: 123 } }); // 组件中访问 export default { mounted() { console.log(this.$route.query.id); } };命名路由:通过命名路由传递参数,可以在路由定义时指定
name属性,然后在跳转时通过params传递参数。// www.javascriptcn.com code example // 路由定义 const routes = [ { path: '/user/:id', name: 'user', component: User } ]; // 路由跳转 this.$router.push({ name: 'user', params: { id: 123 } }); // 组件中访问 export default { mounted() { console.log(this.$route.params.id); } };编程式导航:通过
this.$router.push或this.$router.replace方法进行编程式导航时,可以直接传递参数。// www.javascriptcn.com code example // 路由跳转 this.$router.push({ path: '/user', query: { id: 123 } }); // 组件中访问 export default { mounted() { console.log(this.$route.query.id); } };
本题详细解读
动态路由参数
动态路由参数是 Vue Router 中最常用的传递参数的方式之一。通过在路由路径中使用 :param 的形式定义动态路由参数,可以在组件中通过 this.$route.params 访问这些参数。这种方式适用于需要在 URL 中直接体现参数值的场景。
查询参数
查询参数是通过在 URL 中使用 ?key=value 的形式传递的。这种方式适用于不需要在 URL 路径中直接体现参数值的场景,比如分页、筛选等。在组件中可以通过 this.$route.query 访问这些参数。
命名路由
命名路由是通过在路由定义时指定 name 属性,然后在跳转时通过 params 传递参数的方式。这种方式适用于需要在多个地方使用相同的路由路径,但传递不同参数的场景。在组件中可以通过 this.$route.params 访问这些参数。
编程式导航
编程式导航是通过 this.$router.push 或 this.$router.replace 方法进行路由跳转时传递参数的方式。这种方式适用于在代码中动态决定路由跳转的场景。在组件中可以通过 this.$route.query 或 this.$route.params 访问这些参数。
通过以上几种方式,可以在 Vue Router 中灵活地传递和获取路由参数,满足不同的业务需求。