Vue3 watchEffect高级监听器
Vue3 watchEffect高级监听器
watchEffect
export declare function watchEffect(effect: WatchEffect, options?: WatchOptionsBase): WatchStopHandle;
立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。
<script setup lang="ts">
import {
ref, reactive, watchEffect} from "vue";
let msg1 = ref<string>(msg1)
let msg2 = ref<string>(msg2)
watchEffect(()=>{
console.log("msg1:", msg1.value)
console.log("msg2:", msg2.value)
})
</script>
<template>
<div>
<input type="text" v-model="msg1">
<input type="text" v-model="msg2">
</div>
</template>
回调参数oninvalidate,在回调函数之前执行
<script setup lang="ts">
import {
ref, reactive, watchEffect} from "vue";
let msg1 = ref<string>(msg1)
let msg2 = ref<string>(msg2)
watchEffect((oninvalidate)=>{
console.log("msg1:", msg1.value)
console.log("msg2:", msg2.value)
oninvalidate(()=>{
//
console.log("before----------------")
})
})
</script>
<template>
<div>
<input type="text" v-model="msg1">
<input type="text" v-model="msg2">
</div>
</template>
停止监听
<script setup lang="ts">
import {
ref, reactive, watchEffect} from "vue";
let msg1 = ref<string>(msg1)
let msg2 = ref<string>(msg2)
const stop = watchEffect((oninvalidate)=>{
console.log("msg1:", msg1.value)
console.log("msg2:", msg2.value)
oninvalidate(()=>{
//
console.log("before----------------")
})
})
const stopWatch = () => {
stop()
}
</script>
上一篇:
IDEA上Java项目控制台中文乱码
