vue2+vue3前端防抖(例如输入框)
vue3
点击查看代码
<script lang="ts" setup>
import {ref, watchEffect,reactive} from 'vue'
const antiShake = (val1: any, val2: any, time: number) => {
return setTimeout(() => {
interval.min = val1;
interval.max = val2;
console.log(`min:${val1},max${val2}`);
}, time);
};
// 输入
const state = reactive<any>({
min: undefined,
max: undefined,
});
watchEffect((onInvalidate) => {
const timer = antiShake(state.min, state.max, 2000);
onInvalidate(() => clearTimeout(timer));
});
</script>
<template>
<div class="price">
<InputNumber v-model:value="state.min" prefix="¥" :min="0" />
<span class="split">-</span>
<InputNumber v-model:value="state.max" prefix="¥" :min="0" />
</div>
<template>
vue2
// 防抖 立即执行
function debounce(fn, arg) {
// delay = delay || 1000;
let delay = 1000;
let timeout;
return function() {
let context = this;
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, delay);
if (callNow) fn.apply(context, arg);
};
}
export { debounce };
import Vue from 'vue';
import { debounce } from '@/utils';
Vue.directive('debounce', {
bind(el, binding) {
const [fn, ...args] = binding.value;
el.addEventListener('click', debounce(fn, args));
},
unbind(el, binding) {
const [fn, ...args] = binding.value;
el.removeEventListener('click', debounce(fn, args));
}
});
// 要执行的函数
handleDownload() {
console.log()
},
「vue2为摘抄版本」

浙公网安备 33010602011771号