Vue3使用customRef实现防抖

当用户频繁的点击请求按钮的时候,我们可以使用防抖的方式让其不会一直向后端发送请求。

customRef 是个工厂函数要求我们返回一个对象 并且实现 get 和 set  适合去做防抖之类的。

点击按钮

<template>
  <hr>
  <div>
    {
   
   { name }}
  </div>
  <hr>
  <button @click="change">修改 customRef</button>
 
</template>
 
<script setup lang='ts'>
import { ref, customRef } from 'vue'
 
function myRef<T = any>(value: T) {
  let timer:any;
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newVal) {
        clearTimeout(timer)
        timer =  setTimeout(() => {
          console.log('触发了set')
          value = newVal
          trigger()
        },500)
      }
    }
  })
}
 
 
const name = myRef<string>('修改前')
 
 
const change = () => {
  name.value = '修改后'
}
 
</script>
<style scoped>
</style>

猜你喜欢

转载自blog.csdn.net/weixin_42078172/article/details/127239239