import { customRef } from "vue";
/**
* @description 自定义ref实现防抖
* @param {String} value
* @param {Number} delay
* @returns
*/
export const debounceRef = (value,delay) => {
let timer;
return customRef((track,trigger) => ({
get(){
// 依赖收集
track();
return value
},
set(val){
clearTimeout(timer);
timer = setTimeout(() => {
value = val;
// 派发更新
trigger()
},delay)
}
}))
}
//使用
<template>
<input type="text" v-model="value">
<h3>{{ value }}</h3>
</template>
<script setup>
import { debounceRef } from "../utils/debounce";
const value = debounceRef('',1000)
</script>