在 Vue 3 的组合式 API 中,如何正确地监听一个响应式对象的深层属性变化?
Author: 图恩Category: 编程开发Views: 155Published: 2025-10-31 **How to correctly listen to deep properties of a reactive object in Vue 3's Composition API**
**Answer:**
In Vue 3's Composition API, to listen to changes in deep properties of a reactive object, use the `watch` function and set the `deep: true` option.
**Example Code:**
```javascript
import { ref, watch } from 'vue';
const user = ref({
name: 'Alice',
address: {
city: 'Beijing',
street: 'Chaoyang'
}
});
watch(
user,
(newVal, oldVal) => {
console.log('user changed:', newVal);
},
{ deep: true }
);
```
**Explanation:**
- By default, `watch` only monitors changes to the reference itself, not internal properties of the object.
- The `deep: true` option enables **deep monitoring**, triggering the callback whenever any nested property of the object changes.
- **Performance considerations**: Deep monitoring incurs additional overhead. Avoid using it excessively on large or frequently changing objects.
- For targeted monitoring of specific deep properties (e.g., `user.value.address.city`), a more efficient approach is to directly watch the path, such as:
```javascript
watch(() => user.value.address.city, (newVal) => {
console.log('city changed:', newVal);
});
```
**Key Points:**
1. **Deep Monitoring**: Requires `deep: true` to track nested property changes.
2. **Performance Trade-off**: Deep monitoring increases resource usage.
3. **Alternative Optimization**: Directly watch specific properties (e.g., `address.city`) for targeted updates.
This approach balances functionality with performance efficiency.