Vue3 customRef简单防抖实例

50 阅读1分钟

customRef简单防抖案例

以下是一个我在网上学习到的简单的Vue3 customRef小案例。 目的是为了减少点击按钮频繁调用API对服务器的压力 image.png

<template>
  <div>
    {{obj}}
  </div>
  <hr>
  <button @click="change">修改</button>
</template>

<script setup lang="ts">
import {customRef} from "vue";
const obj = MyRef<string>("customRef: YFM")
// customRef简单防抖案例
// 减少频繁调用API是对服务器的压力
function MyRef<T>(value: T) {
  let timer: any
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timer)
        timer = setTimeout(() => {
          console.log('触发了')
          value = newValue
          timer = null
          trigger()
        }, 500)
      }
    }
  })
}
const change = () => {
  obj.value = "customRef 修改了"
}
</script>

<style scoped>

</style>