When the user frequently clicks the request button, we can use the anti-shake method to prevent it from sending requests to the backend all the time.
customRef is a factory function that requires us to return an object and implement get and set, suitable for anti-shake and the like.
click button
<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>