Skip to content

23 - 自定义ref #2962

Open
Open
@XiaoPingzi-Anhui

Description

@XiaoPingzi-Anhui
// 你的答案
<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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions