Open alirezamou opened 1 year ago
<script setup> import { watch, isRef, unref, computed, ref } from "vue" /** * Implement the function */ function useDebouncedRef(value, delay = 200) { let rawValue = isRef(value) ? value.value : value; const rawValueRef = ref(rawValue); let timerId; return computed({ get: () => rawValueRef.value, set: (newValue) => { clearTimeout(timerId); timerId = setTimeout(() => rawValueRef.value = newValue, delay); } }); } const text = useDebouncedRef("hello"); /** * Make sure the callback only gets triggered once when entered multiple times in a certain timeout */ watch(text, (value) => { console.log(value) }) </script> <template> <input v-model="text" /> </template>
isRef可以使用unref更好
这里好像并不需要判断是否为原始值,ref可以接受另一个ref