Skip to content

23 - 自定义ref #1769

Open
Open
@webfanzc

Description

@webfanzc
<script setup>
import { watch, ref, computed } from 'vue';
/**
 * Implement the function
 */
function useDebouncedRef(value, delay = 200) {
  const refValue = ref(value);

  const changeHandler = (val) => {
    refValue.value = val;
  };
  const dobouncedChangeFunc = debounced(changeHandler, delay);
  const valueComputed = computed({
    get: () => {
      return refValue.value;
    },
    set: (val) => {
      dobouncedChangeFunc(val);
    },
  });

  return valueComputed;
}
  
function debounced(fn, delay) {
  let timer = null;

  return (...args) => {
    timer && clearTimeout(timer);
    timer = setTimeout(fn, delay, ...args);
  }
}
const text = useDebouncedRef('hello');
// console.log('text', text);
/**
 * 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" />
  {{ 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