1.watchEffect
立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。
包含两个参数:
- 参数一:要运行的副作用函数,该函数有一个参数,这个参数也是一个函数类型,用来注册清理回调。清理回调会在该副作用下一次执行前被调用,可以用来清理无效的副作用。
- 参数二:配置项。
<template>
<div>姓名:<input type="text" v-model="name" /></div>
<div>年龄:<input type="number" v-model="age" /></div>
</template>
<script setup lang="ts">
import { ref, reactive, watchEffect } from 'vue'
const name = ref<string>('张三')
const age = ref<number>(20)
watchEffect((oninvalidate) => {
console.log('watchEffect', name.value)
console.log('watchEffect', age.value)
oninvalidate(() => {
console.log('before')
})
})
</script>
立即执行一次,当数据发生改变时触发:
(1)清除副作用函数:
<template>
<div>姓名:<input type="text" v-model="name" /></div>
<div>年龄:<input type="number" v-model="age" /></div>
<button @click="handleStop">停止watchEffect</button>
</template>
<script setup lang="ts">
import { ref, reactive, watchEffect } from 'vue'
const name = ref<string>('张三')
const age = ref<number>(20)
const stop = watchEffect((oninvalidate) => {
console.log('watchEffect', name.value)
console.log('watchEffect', age.value)
oninvalidate(() => {
console.log('before')
})
})
const handleStop = () => {
stop()
}
</script>
这段代码中改变 name 和 age 的值后,点击按钮停止侦听:
可以看到,点击按钮停止侦听后,只运行了副作用函数中的参数,并没有继续侦听数据的改变。
(2)配置项
-
flush :副作用刷新时机,一般使用 post ;
-
onTrack :帮助调试 watchEffect ;
-
onTrigger :帮助调试 watchEffect 。