乐闻世界logo
搜索文章和话题

How to get params of router in Vue 3?

1个答案

1

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:

  1. Import useRoute: In your component, first import the useRoute function from the vue-router package.
javascript
import { useRoute } from 'vue-router';
  1. Use useRoute to retrieve route information: Within the component's setup function, call the useRoute function. This returns a reactive object containing the current route information.
javascript
setup() { const route = useRoute(); return { // Access params directly from the route object params: route.params, }; }
  1. Access the params property: The params property of the route object contains all route parameters. You can directly access specific route parameters using route.params.
javascript
setup() { 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:

javascript
const 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.

2024年6月29日 12:07 回复

你的答案