vue3防抖函数封装与使用,以指令的形式使用

utils/debounce.js

/**
 * 防抖函数
 * @param {*} fn 函数
 * @param {*} delay 暂停时间
 * @returns 
 */
export function debounce(fn, delay = 500) {
  
    let timer = null
    return function (...args) {
      // console.log(arguments);
      // const args = Array.from(arguments)
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.apply(this, args)
      }, delay)
    }
  }

main.js 定义全局化指令

import { createApp } from 'vue'
import App from './App.vue'
import { debounce } from './utils/debounce'

const app = createApp(App)

// 创建全局指令
app.directive('debounce', {
  mounted(el, binding) {
    const { value, arg } = binding
    const debouncedFn = debounce(value, arg)
    el.addEventListener('click', debouncedFn) // 将事件改为click
  },
  beforeUnmount(el, binding) {
    const { value } = binding
    el.removeEventListener('click', value)
  }
})

app.mount('#app')

指令的使用



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