Vue防抖debounce

在搜索框中随着输入内容而更新显示内容或者需要请求接口等逻辑时,如果每一个字符变化都去更新则会浪费一些没有必要的请求,想要的结果是某一个时间内不要去更新,就是常用的防抖测略

Vue中防抖逻辑:在响应式的变量在包装一个响应式,新的响应式只有在一定时间到时才更新,具体如下

export function useDebounce<T>(value: Ref<T>, delay: number) {
  const debounceValue = ref(value.value)
  let timer: number | null = null
  const unwatch = watch(value, (nv) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      debounceValue.value = nv as UnwrapRef<T>
    }, delay)
  })

  onUnmounted(() => {
    unwatch()
  })
  return debounceValue
}

 试用也很简单:

1秒内不更新相应
const debounceValue = useDebounce(searchValue, 1000)
watch(debounceValue, (nv) => {
  if (!nv) {
    searchResult.value = []
    return
  }
  onSearch(nv as string)//具体更新的逻辑
})

 

posted @ 2023-11-09 20:31  不停奔跑的蜗牛  阅读(168)  评论(0编辑  收藏  举报