Retrieving route parameters in Vue 3 is typically done when using Vue Router. There are two primary types of parameters to consider: path parameters (params) and query parameters (query). Here's how to retrieve each type:
1. Retrieving Path Parameters (params)
Path parameters are defined in the URL path using :. For example, in a route configuration like /user/:id, :id represents a path parameter.
In Vue 3 components, you can access these parameters using useRoute().params. For instance:
javascriptexport default { mounted() { // Retrieve the path parameter named 'id' const userId = useRoute().params.id; console.log("User ID:", userId); } }
2. Retrieving Query Parameters (query)
Query parameters appear after ? in the URL, such as keyword=vue in /search?keyword=vue.
In Vue 3 components, these query parameters can be accessed using useRoute().query. For example:
javascriptexport default { mounted() { // Retrieve the query parameter named 'keyword' const keyword = useRoute().query.keyword; console.log("Search keyword:", keyword); } }
Practical Example
Suppose you have a user detail page with the following route configuration:
javascript// In router/index.js const routes = [ { path: '/user/:id', name: 'UserDetail', component: () => import('../views/UserDetail.vue') } ];
In UserDetail.vue, you can retrieve the user ID as follows:
javascriptexport default { name: "UserDetail", mounted() { // Retrieve the user ID const userId = useRoute().params.id; console.log("User ID:", userId); // Perform other operations, such as fetching user details via an API } }
This approach ensures that regardless of how /user/123 is accessed, the component correctly parses the user ID as 123 and proceeds with subsequent operations.
In summary, by using useRoute().params and useRoute().query, you can efficiently retrieve all route parameters in Vue 3, which is invaluable for building dynamic pages and handling user interactions.