<!-- 小贴士: 🎉 恭喜你成功解决了挑战,很高兴看到你愿意分享你的答案! 由于用户数量的增加,Issue 池可能会很快被答案填满。为了保证 Issue 讨论的效率,在提交 Issue 前,请利用搜索查看是否有其他人分享过类似的档案。 你可以为其点赞,或者在 Issue 下追加你的想法和评论。如果您认为自己有不同的解法,欢迎新开 Issue 进行讨论并分享你的解题思路! 谢谢! --> ```vue // 你的答案 ``` <script setup> import { computed } from "vue"; import { watch,ref , customRef} from "vue" /** * Implement the function */ function useDebouncedRef(value, delay = 1000) { /** const v = ref(value); let timer = null; const c = computed({ get(){ return v.value }, set(newV){ if(timer){ clearTimeout(timer); } timer = setTimeout(()=>{ v.value =newV },delay) } })*/ let _v = value; let timer = null; return customRef((track,trigger)=>{ return { get:()=>{ track() return _v }, set:(newV)=>{ if(timer) clearInterval(timer) timer=setTimeout(()=>{ _v = newV trigger() },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> <!-- 或者 Vue SFC Playground 在线链接 (https://sfc.vuejs.org) -->