Vue 3 中如何在组合式 API(Composition API)中监听路由参数的变化?
Author: 图恩Category: 编程开发Views: 161Published: 2025-11-03 **How to listen to route parameter changes in Composition API of Vue 3**
**Answer:**
In Vue 3's Composition API, you can use the `watch` function in conjunction with `useRoute` to monitor changes in route parameters. The key steps are as follows:
1. **Import necessary modules**
```js
import { watch } from 'vue';
import { useRoute } from 'vue-router';
```
2. **Access the current route object**
```js
const route = useRoute();
```
3. **Listen for parameter changes**
- For individual parameters (e.g., `/user/:id`):
```js
watch(
() => route.params.id,
(newId, oldId) => {
console.log('ID changed from', oldId, 'to', newId);
// Implement data fetching or state updates here
}
);
```
- For entire `params` object (multiple parameters):
```js
watch(
() => ({ ...route.params }),
(newParams) => {
console.log('Params changed:', newParams);
}
);
```
**Parsing Explanation:**
- `useRoute()` returns a reactive route object, but its internal properties (e.g., `params`, `query`) are not reactive references. Direct `watch(route.params)` is invalid; instead, use a getter function or destructuring to trigger reactive tracking:
```js
watch(() => route.params.id, ...);
```
- This approach is ideal for re-fetching data or updating states when switching between different route parameters (e.g., `/user/1` → `/user/2`).
- **Important Notes:**
- **Script Setup Syntax:** The logic remains identical, with `watch` and `useRoute` used at the top level.
- **Alternative to Vue 2:** This method replaces Vue 2's `$route` watch or `beforeRouteUpdate` navigation guard, aligning with Vue 3's composition API reactive programming model.
**Key Advantages:**
- **Simplicity:** Directly uses `watch` and `useRoute` without complex setup.
- **Reactivity:** Ensures proper reactive tracking through getter functions or object destructuring.
- **Flexibility:** Supports both single-parameter and multi-parameter monitoring.
This pattern is preferred over Vue 2's imperative approach, offering a more declarative and maintainable solution.