1、说明:
2、lodash的debounce
"lodash": "^4.17.21",
pnpm add lodash
<template>
<button @click="debouncedButtonClick">Click me</button>
</template>
<script setup>
import { debounce } from 'lodash';
const debouncedButtonClick = debounce(() => {
console.log('Button Clicked');
}, 2000);
</script>
多次点击按钮,会在最后一次点击以后的2s,输出Button Clicked。
2、@vueuse/core的useDebounceFn
"@vueuse/core": "^11.0.3",
pnpm add @vueuse/core
<template>
<button @click="debouncedButtonClick">Click me</button>
</template>
<script setup>
import {useDebounceFn} from '@vueuse/core';
const debouncedButtonClick = useDebounceFn(() => {
console.log('Button Clicked');
}, 2000);
</script>
3、setTimeout
<template>
<button @click="debouncedButtonClick">Click me</button>
</template>
<script setup>
let timeout = null;
const debouncedButtonClick = () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log('Button Clicked');
}, 2000);
};
</script>
以上事例修改于baidu ai。
4、运行效果:
各种测试,多次点击按钮,会在最后一次点击以后的2s,输出Button Clicked。