[ uniapp ] 在uniapp中使用防抖函数
/** * 防抖函数 * @param {Function} fn - 需要防抖处理的函数 * @param {number} delay - 延迟时间(毫秒) * @param {boolean} immediate - 是否立即执行 * @returns {Function} - 返回防抖后的函数 */ export default function (fn, delay = 300, immediate = false) { let timer = null; let isExecuted = false; return function (...args) { const context = this; // 清除前一个定时器 if (timer) clearTimeout(timer); // 立即执行的逻辑 if (immediate && !isExecuted) { fn.apply(context, args); isExecuted = true; } // 设置新的定时器 timer = setTimeout(() => { if (!immediate) { fn.apply(context, args); } isExecuted = false; timer = null; }, delay); } }
uniapp vue2 中使用
import debounce from '@/utils/debounce.js' export default { data() { return {}; }, methods: { // 取消弹窗 // test() { // console.log('hello world') // } // 改写为 // 这里一定要用function, 用箭头函数会导致防抖函数里面的this指向undefined test: debounce(function () { console.log('hello world') }) }, };
本想把生活活成一首诗, 时而优雅 , 时而豪放 , 结果活成了一首歌 , 时而不靠谱 , 时而不着调

浙公网安备 33010602011771号