<template>
<div>
<input type="text" name="" id="" v-model="keyword">
<div>{{keyword}}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, customRef } from "vue";
function useDebouncedRef<T>(value: T,delay=200) {
let timeout: number
return customRef((track,trigger) => {
return{
get(){
//告诉vue追踪数据
track()
return value
},
set(newValue: T){
clearTimeout(timeout)
timeout = setTimeout(() => {
//更换数据
value = newValue
//告诉vue去触发页面更新
trigger()
},delay)
}
}
})
}
export default defineComponent({
name: "App",
setup() {
//第一个参数为设置keyword的初始值,第二个参数为延迟更新的时间
const keyword = useDebouncedRef('aaa',500)
return{
keyword
}
},
})
</script>