Skip to content

23 - custom ref #2130

Open
Open
@alirezamou

Description

@alirezamou
<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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions