<template>
<!-- 防抖 -->
<div class="">搜索:<input type="text" @keyup="search" v-model="item" /></div>
<!-- 节流 -->
<div class="">
搜索2:<input type="text" @keyup="searchThrottle" v-model="itemThrottle" />
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const item = ref();
export const itemThrottle = ref();
// 防抖
const debounce = (fn: any, delay: number) => {
let timer: any = null;
return function (this:object,...args: any) {
let _this = this;
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
timer = null;
fn.apply(_this, args);
}, delay);
};
};
const search = debounce(() => {
console.log(item.value);
}, 1000);
// 节流
export const throttle = (fn: any, delay: number) => {
let timer: any = null;
return function (this:object,...args: any) {
if (timer) return;
const _this = this;
timer = setTimeout(() => {
timer = null;
}, delay);
fn.apply(_this, args);
};
};
const searchThrottle = throttle(() => {
console.log(itemThrottle.value);
}, 2000);
</script>
<style lang="less" scoped></style>
vue3实现防抖和节流
于 2023-11-13 15:23:32 首次发布