vue3下watch的使用
时间: 2023-11-17 14:57:31 浏览: 39
在Vue3中,watch函数用于监听响应式数据的变化,并在数据变化时执行回调函数。watch函数接收两个参数:要监听的数据源和回调函数。当数据源发生变化时,回调函数会被触发。与Vue2不同的是,Vue3中的watch函数不再支持深度监听,而是需要手动设置deep选项来实现深度监听。此外,Vue3还引入了watchEffect函数,它可以自动跟踪回调的响应式依赖,从而简化代码。watchEffect函数会自动追踪回调函数中使用到的响应式数据,并在数据变化时重新执行回调函数。与watch函数不同的是,watchEffect函数不需要指定要监听的数据源,它会自动追踪回调函数中使用到的响应式数据。
下面是一个使用watch函数的例子:
```
<template>
<div>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</div>
</template>
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
watch(count, (newValue, oldValue) => {
console.log(`count从${oldValue}变为${newValue}`)
})
</script>
<style>
</style>
```
在上面的例子中,我们使用watch函数监听count变量的变化,并在变化时打印出变化前后的值。
下面是一个使用watchEffect函数的例子:
```
<template>
<div>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</div>
</template>
<script setup>
import { ref, watchEffect } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
watchEffect(() => {
console.log(`count的值为${count.value}`)
})
</script>
<style>
</style>
```
在上面的例子中,我们使用watchEffect函数自动追踪count变量的变化,并在变化时打印出count的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)