webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.72k stars 187 forks source link

23 - custom ref #2130

Open alirezamou opened 1 year ago

alirezamou commented 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>
undefined-zzk commented 9 months ago

isRef可以使用unref更好

slowpack commented 8 months ago

这里好像并不需要判断是否为原始值,ref可以接受另一个ref