How do I pass routing parameters in Vue 3 differently and get them in a component using defineProps or other combined API?
1. Pass through path parameter
The most common way is to pass the parameters as props to the component by defining dynamic parameters in the routing path and setting props: true in the routing configuration.
Routing configuration
{ path: '/:projectId(\\d+)/report/calc/:reportId(\\d+)', name: 'CreateCalcPage', component: () => import('@/pages/report/'), props: true, // Pass routing parameters through props}
Use defineProps in components
<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. Pass through query parameter
Can be passedquery
Parameters pass data. In this case, it is necessary to manuallyroute
Get parameters in the object.
Routing jump
({ name: 'CreateCalcPage', query: { projectId: '123', reportId: '456', }, });
Use useRoute in components
<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 = ; const reportId = ; </script>
3. Pass through the props option
Can be used in routing configurationprops
Options to pass static or dynamic parameters.
Static parameters
{ path: '/report/calc', name: 'CreateCalcPage', component: () => import('@/pages/report/'), props: { projectId: '123', reportId: '456' }, }
Dynamic parameters
{ path: '/report/calc', name: 'CreateCalcPage', component: () => import('@/pages/report/'), props: route => ({ projectId: , reportId: }), }
Use defineProps in components
<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>
Summarize
-
pass
path
Parameter passing: Define dynamic parameters in the routing path and useprops: true
Pass it as props. -
pass
query
Parameter passing: Passed when the route jumpsquery
Parameters pass data and use it in componentsuseRoute
Get it. -
pass
props
Option passing: Used in routing configurationprops
Options pass static or dynamic parameters.
This is the introduction to this article about the three ways to pass routing parameters in Vue3. For more related content on Vue3, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!