防抖
<template><button id="submitButton" ref="submitButton">GET</button>
</template><script lang="ts" setup>
import { ref, onMounted } from 'vue';// 防抖函数
function debounce(func: () => void, delay: number) {let timer: number;return function () {clearTimeout(timer);timer = window.setTimeout(() => {func();}, delay);};
}// 使用 ref 访问 DOM 元素
const submitButton = ref<HTMLElement | null>(null);onMounted(() => {if (submitButton.value) {submitButton.value.addEventListener('click',debounce(() => {console.log('clicked');}, 1000));}
});
</script><style lang="scss" scoped>
</style>
效果
节流
<template><button id="submitButton" ref="submitButton">GET</button></template><script lang="ts" setup>import { ref, onMounted } from 'vue';// 节流函数function throttle(func: () => void, limit: number) {let inThrottle: boolean;return function (...args: any[]) {if (!inThrottle) {func(...args);inThrottle = true;setTimeout(() => inThrottle = false, limit);}};}// 使用 ref 访问 DOM 元素const submitButton = ref<HTMLElement | null>(null);onMounted(() => {if (submitButton.value) {submitButton.value.addEventListener('click',throttle(() => {console.log('clicked');}, 1000));}});</script><style lang="scss" scoped></style>