Skip to content

23 - 自定义ref #2962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
XiaoPingzi-Anhui opened this issue Apr 16, 2025 · 0 comments
Open

23 - 自定义ref #2962

XiaoPingzi-Anhui opened this issue Apr 16, 2025 · 0 comments

Comments

@XiaoPingzi-Anhui
Copy link

// 你的答案
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant