vue3watch 配置
时间: 2023-09-12 12:10:54 浏览: 129
在Vue 3中,watch函数的配置有以下几种方式:
1. 监视ref(监视基本类型):
```javascript
const money = ref(100);
watch(money, (newVal, oldVal) => {
console.log("money变化了", newVal, oldVal);
});
```
2. 监视reactive(监视复杂类型):
```javascript
const state = reactive({
money: 100,
car: { brand: "宝马" }
});
watch(state, (newVal, oldVal) => {
console.log("state变化了", newVal, oldVal);
});
```
3. 监视对象里面的属性,属性的值是基本类型:
```javascript
const state = reactive({
money: 100,
car: { brand: "宝马" }
});
watch(() => state.money, (newVal, oldVal) => {
console.log("state.money变化了", newVal, oldVal);
});
```
4. 监视对象里面的属性,属性的值是复杂类型:
```javascript
const state = reactive({
money: 100,
car: { brand: "宝马" }
});
watch([() => state.car.brand], (newVal, oldVal) => {
console.log("state.car.brand变化了", newVal, oldVal);
});
```
5. 监视reactive定义的响应式数据中的某些属性:
```javascript
watch([() => person.job, () => person.name], (newValue, oldValue) => {
console.log('person的job或name变化了', newValue, oldValue);
}, { immediate: true, deep: true });
```
在以上示例中,watch函数的第一个参数可以是一个ref、reactive对象,也可以是返回需要监视的属性的函数。第二个参数是回调函数,用于处理属性的变化。可以通过配置对象作为watch函数的第三个参数,进行额外的配置,如immediate和deep参数。其中immediate参数表示立即侦听(页面一刷新就会监听),deep参数表示深度侦听。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [vue3之watch](https://blog.csdn.net/qq_52421092/article/details/131067716)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [【vue笔记】vue3中的watch函数配置功能以及两个小坑](https://blog.csdn.net/ONLYSRY/article/details/125725832)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文