Vue 防抖节流函数与指令

直接上代码:

/**
 * 防抖
 * @param {*} func
 * @param {*} wait
 * @returns
 */
function debounce(func, wait = 300) {
  let timeout;
  return function (...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

// 使用示例
window.addEventListener(
  "resize",
  debounce(function () {
    console.log("窗口大小改变");
  }, 250)
);

/**
 * 节流
 * @param {*} func
 * @param {*} limit
 * @returns
 */
function throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function (...args) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if (Date.now() - lastRan >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

// 使用示例
window.addEventListener(
  "scroll",
  throttle(function () {
    console.log("滚动事件");
  }, 1000)
);

/**
 * 防抖指令(v-debounce)
 * 
 * 
滚动区域
; */ Vue.directive("debounce", { bind(el, { value, arg: delay = 300, modifiers }) { const { handler, events = ["click"] } = typeof value === "function" ? { handler: value } : value; const debouncedFn = debounce(handler, delay); // 支持多事件绑定(如 click、scroll) events.forEach((event) => el.addEventListener(event, debouncedFn)); el._debounceEvents = events.map((event) => ({ event, fn: debouncedFn })); }, unbind(el) { // 组件销毁时移除监听 el._debounceEvents?.forEach(({ event, fn }) => { el.removeEventListener(event, fn); }); }, }); /** * 节流指令(v-throttle) *
滚动加载容器
* ; */ // 核心逻辑‌:ml-citation{ref="1,2" data="citationList"} Vue.directive("throttle", { bind(el, { value, arg: interval = 1000, modifiers }) { const { handler, events = ["scroll"] } = typeof value === "function" ? { handler: value } : value; const throttledFn = throttle(handler, interval); events.forEach((event) => el.addEventListener(event, throttledFn)); el._throttleEvents = events.map((event) => ({ event, fn: throttledFn })); }, unbind(el) { el._throttleEvents?.forEach(({ event, fn }) => { el.removeEventListener(event, fn); }); }, });

你可能感兴趣的:(Vue,vue.js,javascript,ecmascript)