Skip to content

23 - 自定义ref #3078

@baieme

Description

@baieme
<script setup>
import { watch, customRef } from "vue"

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions