如何通过不同方式在 Vue 3 中传递路由参数,并在组件中使用 defineProps 或其他组合式 API 获取这些参数?
1. 通过 path 参数传递
 
最常见的方式,通过在路由路径中定义动态参数,并在路由配置中设置 props: true,将参数作为 props 传递给组件。
路由配置
{path: '/:projectId(\\d+)/report/calc/:reportId(\\d+)',name: 'CreateCalcPage',component: () => import('@/pages/report/calc.vue'),props: true, // 通过 props 传递路由参数
}
组件中使用 defineProps
 
<template><div><p>Project ID: {{ projectId }}</p><p>Report ID: {{ reportId }}</p></div>
</template><script setup>
import { defineProps } from 'vue';const props = defineProps({projectId: {type: String,required: true,},reportId: {type: String,required: true,},
});
</script>
2. 通过 query 参数传递
 
可以通过 query 参数传递数据。在这种情况下,需要手动从 route 对象中获取参数。
路由跳转
router.push({name: 'CreateCalcPage',query: {projectId: '123',reportId: '456',},
});
组件中使用 useRoute
 
<template><div><p>Project ID: {{ projectId }}</p><p>Report ID: {{ reportId }}</p></div>
</template><script setup>
import { useRoute } from 'vue-router';const route = useRoute();
const projectId = route.query.projectId;
const reportId = route.query.reportId;
</script>
3. 通过 props 选项传递
 
可以在路由配置中使用 props 选项来传递静态或动态参数。
静态参数
{path: '/report/calc',name: 'CreateCalcPage',component: () => import('@/pages/report/calc.vue'),props: { projectId: '123', reportId: '456' },
}
动态参数
{path: '/report/calc',name: 'CreateCalcPage',component: () => import('@/pages/report/calc.vue'),props: route => ({ projectId: route.query.projectId, reportId: route.query.reportId }),
}
组件中使用 defineProps
 
<template><div><p>Project ID: {{ projectId }}</p><p>Report ID: {{ reportId }}</p></div>
</template><script setup>
import { defineProps } from 'vue';const props = defineProps({projectId: {type: String,required: true,},reportId: {type: String,required: true,},
});
</script>
总结
- 通过 path参数传递:在路由路径中定义动态参数,并使用props: true将其作为 props 传递。
- 通过 query参数传递:在路由跳转时通过query参数传递数据,并在组件中使用useRoute获取。
- 通过 props选项传递:在路由配置中使用props选项传递静态或动态参数。