vue3 watchEffect 的使用
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3 watchEffect 的使用相关的知识,希望对你有一定的参考价值。
<template>
<input type="text" v-model="message">
<input type="text" v-model="message2">
</template>
<script setup lang="ts">
import reactive, ref, watch, watchEffect from "vue";
let message = ref<String>("Hello ");
let message2 = ref<String>(" World");
watchEffect(() =>
console.log(message.value, message2.value);
);
</script>
当用到那个ref数据的时候 就会被监听到。不用则不会被监听。非常的时尚。
如果要在之前做一些操作
清除副作用
<template>
<input type="text" v-model="message">
<input type="text" v-model="message2">
</template>
<script setup lang="ts">
import reactive, ref, watch, watchEffect from "vue";
let message = ref<String>("Hello ");
let message2 = ref<String>(" World");
watchEffect((onCleanup) =>
console.log(message.value, message2.value);
onCleanup(() =>
console.log("before");
);
);
</script>
停止监听事件
<template>
<input type="text" v-model="message">
<input type="text" v-model="message2">
<button @click="stopWatch">停止监听</button>
</template>
<script setup lang="ts">
import reactive, ref, watch, watchEffect from "vue";
let message = ref<String>("Hello ");
let message2 = ref<String>(" World");
const stop = watchEffect((oninvalidate) =>
console.log(message.value, message2.value);
oninvalidate(() =>
console.log("before");
);
);
const stopWatch = () => stop();
</script>
赋值新变量给stop 然后直接调用方法就可以停止下来。
<template>
<input id="ipt" type="text" v-model="message">
<input type="text" v-model="message2">
<button @click="stopWatch">停止监听</button>
</template>
<script setup lang="ts">
import reactive, ref, watch, watchEffect from "vue";
let message = ref<String>("Hello ");
let message2 = ref<String>(" World");
const stop = watchEffect((oninvalidate) =>
let ipt: htmlInputElement = document.getElementById("ipt") as HTMLInputElement;
// console.log(message.value, message2.value);
console.log(ipt, "e11111");
oninvalidate(() =>
console.log("before");
);
, flush: "post");
const stopWatch = () => stop();
</script>
以上是关于vue3 watchEffect 的使用的主要内容,如果未能解决你的问题,请参考以下文章
vue3 watch监听 (immediate / deep / watchEffect)
vue3 watch监听 (immediate / deep / watchEffect)
Vue3官网-高级指南(十七)响应式计算`computed`和侦听`watchEffect`(onTrackonTriggeronInvalidate副作用的刷新时机`watch` pre)(代码片段