立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。
如果用到message 就只会监听message
就是用到几个监听几个 而且是非惰性 会默认调用一次
<script setup lang="ts">import { watch, ref, reactive, watchEffect } from "vue";let msg1 = ref<string>("小雪");let msg2 = ref<string>("小满");watchEffect(() => {console.log('msg1',msg1.value);});</script><template><input type="text" v-model="msg1" /><input type="text" v-model="msg2" /></template>
清除副作用
就是在触发监听之前会调用一个函数,可以处理你的逻辑例如防抖
import { watchEffect, ref } from 'vue'let message = ref<string>('')let message2 = ref<string>('')watchEffect((oninvalidate) => {console.log('message', message.value);oninvalidate(()=>{console.log("before");})console.log('message2', message2.value);})
停止跟踪 watchEffect 返回一个函数 调用之后将停止更新
更多的配置项
副作用刷新时机 flush 一般使用post
| pre | sync | post | |
|---|---|---|---|
| 更新时机 | 组件更新前执行 | 强制效果始终同步触发 | 组件更新后执行 |
<script setup lang="ts">import { watch, ref, reactive, watchEffect } from "vue";let msg1 = ref<string>("小雪");let msg2 = ref<string>("小满");const stop = watchEffect((oninvalidate) => {const ipt: HTMLInputElement = document.querySelector("#ipt") as HTMLInputElement;console.log("ipt", ipt);console.log("msg1", msg1.value);oninvalidate(() => {console.log("before");});},{flush: "post",});const stopWatch = stop();</script><template><input id="ipt" type="text" v-model="msg1" /><input type="text" v-model="msg2" /><button @click="stopWatch">停止监听</button></template>
