vue3的watch终止监听,只需要将watch赋值给一个变量,当达到条件调用watch赋值的那个变量就可以终止监听了。
<template><div>{{ data.val }}<button @click="add">加一</button></div>
</template>
<script setup lang="ts">
import { watch, reactive } from "vue";
let data = reactive({val: 2,
});
const flag = watch(() => data.val,(val: any) => {console.log(val); // 3456if (val >= 6) {// 只要将 flag 声明的函数调用就可以结束监听了flag();}},{ deep: true }
);function add() {data.val++;
}
</script>
开启监听:把监听器重新赋值给变量
flag = watch(() => data.val,(val: any) => {console.log(val); // 3456},{ deep: true }
);