vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

23 - 自定义ref

Open kalu5 opened this issue 2 years ago • 0 comments

// 你的答案
<script setup>
import { watch, customRef } from "vue"

/**
 * Implement the function
*/
function useDebouncedRef(value, delay = 200) {
  let timer = null;
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newVal) {
        clearTimeout(timer)
        timer = setTimeout(() => {
          if (value !== newVal) value = newVal
          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>

kalu5 avatar Sep 19 '22 03:09 kalu5