vue2與vue3防抖處理


vue2的防抖處理(自定義指令)

在utils/index.js 文件中

// 防抖 立即執行
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 };

src/directive/index.js 自定義指令:

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));
  }
});

使用:

<el-button v-debounce="[handleDownload]">下載模版</el-button>
 
   // 要執行的函數
    handleDownload() {
     console.log()
    },

 vue3的防抖處理(自定義ref)

<template>
  <input v-model="message" />
  <h2>{{ message }}</h2>
</template>

import {debouncedRef} from '../hooks/debounce.js'

export default {
    setup() {
         const message = debouncedRef('哈哈')
         return {
             message
         };
    }
}
debounce.js
import {
  costomRef
} from 'vue'
export function debouncedRef(value, delay = 200) {
  let timeout;
  return costomRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          value = newValue;
          trigger()
        }, delay)
      }
    }
  })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM