In Vue 3, retrieving router params can be achieved using several methods provided by Vue Router. Vue Router offers a composition API that allows you to access current route information, including route parameters (params). Below, I will detail how to use this method in Vue 3 to retrieve params.
First, ensure you have installed and configured Vue Router in your Vue 3 project. Then, you can use the following steps in any component to retrieve route parameters:
- Import
useRoute: In your component, first import theuseRoutefunction from thevue-routerpackage.
javascriptimport { useRoute } from 'vue-router';
- Use
useRouteto retrieve route information: Within the component'ssetupfunction, call theuseRoutefunction. This returns a reactive object containing the current route information.
javascriptsetup() { const route = useRoute(); return { // Access params directly from the route object params: route.params, }; }
- Access the
paramsproperty: Theparamsproperty of therouteobject contains all route parameters. You can directly access specific route parameters usingroute.params.
javascriptsetup() { const route = useRoute(); const userId = route.params.userId; // Assuming URL contains a 'userId' parameter return { userId, }; }
Example:
Assume you have a route definition with a parameter named userId:
javascriptconst router = createRouter({ history: createWebHistory(), routes: [ { path: '/user/:userId', component: User } ], });
In the User component, you can use the above method to retrieve the userId parameter:
javascript<script setup> import { useRoute } from 'vue-router'; const route = useRoute(); const userId = route.params.userId; console.log("Current user ID is:", userId); </script>
Summary:
Using useRoute is the recommended approach in Vue 3 for retrieving route parameters, as it leverages Vue's composition API, offering better organization and maintainability. Ensure your project uses Vue 3 and a compatible version of Vue Router to utilize these features.