vue3watch如何使用
时间: 2023-10-17 20:34:06 浏览: 95
Vue 2.0 侦听器 watch属性代码详解
在Vue3中,使用`watch`函数来监听响应式数据的变化。`watch`函数接受三个参数:`WatcherSource`(要监听的响应式数据)、`Callback`(回调函数)和可选的`WatchOptions`(选项)。
如果想要在初始化时立即执行回调函数,可以设置`immediate: true`。例如:
```javascript
const count = ref(1);
watch(
count,
(newValue, oldValue) => {
console.log('值发生了变更', newValue, oldValue);
},
{ immediate: true }
);
```
如果想要监听多个数据源,可以将这些数据源放在一个数组中,然后传递给`watch`函数。例如:
```javascript
const count = ref(1);
const double = ref(2);
watch(
[count, double],
(newValue, oldValue) => {
console.log('值发生了变更', newValue, oldValue);
},
{ immediate: true }
);
```
通过这种方式,你可以同时监听多个数据的变化,并在变化时执行回调函数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [vue首次赋值不触发watch的解决方法](https://download.csdn.net/download/weixin_38696336/12952605)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [vue3下watch的使用](https://blog.csdn.net/weixin_42349568/article/details/126760186)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文