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

utils/debounce.js

javascript 复制代码
/**
 * 防抖函数
 * @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 定义全局化指令

javascript 复制代码
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')

指令的使用

复制代码
<template>
	<button v-debounce="handleInput" :delay="500">无参</button>
	<button v-debounce="() => handleInput2(1, 2)" :delay="500">传参</button>
</template>
<script>
	export default{
		methods: {
		    handleInput(){
		      console.log('防抖指令的使用');
		    },
		   handleInput2(v1, v2){
		      console.log('接收参数', v1,v2);
		    },
		}
	}
</script>
相关推荐
弓.长.2 小时前
React Native 鸿蒙跨平台开发:实现一个多功能单位转换器
javascript·react native·react.js
南半球与北海道#2 小时前
前端打印(三联纸票据打印)
前端·vue.js·打印
摘星编程2 小时前
React Native for OpenHarmony 实战:ToggleSwitch 切换开关详解
javascript·react native·react.js
满栀5853 小时前
分页插件制作
开发语言·前端·javascript·jquery
qq_406176143 小时前
深入剖析JavaScript原型与原型链:从底层机制到实战应用
开发语言·前端·javascript·原型模式
弓.长.3 小时前
React Native 鸿蒙跨平台开发:BottomSheet 底部面板详解
javascript·react native·react.js
摘星编程4 小时前
React Native for OpenHarmony 实战:Permissions 权限管理详解
javascript·react native·react.js
闲蛋小超人笑嘻嘻4 小时前
Vue 插槽:从基础到进阶
前端·javascript·vue.js
摘星编程4 小时前
React Native for OpenHarmony 实战:SearchBar 搜索栏详解
javascript·react native·react.js
梦6504 小时前
Vue2 与 Vue3 对比 + 核心差异
前端·vue.js