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')

指令的使用

<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>

相关推荐

  1. vue3函数封装使用指令形式使用

    2024-01-06 10:52:05       49 阅读
  2. vue3指令形式使用事件

    2024-01-06 10:52:05       58 阅读
  3. vue使用lodashdebounce函数

    2024-01-06 10:52:05       60 阅读
  4. Vue:封装响应式数据函数

    2024-01-06 10:52:05       43 阅读
  5. vue封装全局节流函数

    2024-01-06 10:52:05       32 阅读
  6. vue3:websocket封装使用

    2024-01-06 10:52:05       51 阅读
  7. VUE3】自定义指令

    2024-01-06 10:52:05       32 阅读
  8. uniapp中函数debounce使用

    2024-01-06 10:52:05       32 阅读
  9. vue 函数

    2024-01-06 10:52:05       46 阅读
  10. Vue3 Hooks函数使用封装

    2024-01-06 10:52:05       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-06 10:52:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-06 10:52:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-06 10:52:05       82 阅读
  4. Python语言-面向对象

    2024-01-06 10:52:05       91 阅读

热门阅读

  1. 使用 openpyxl 库读取 Excel 文件

    2024-01-06 10:52:05       53 阅读
  2. MySQL-DDL

    MySQL-DDL

    2024-01-06 10:52:05      44 阅读
  3. 云计算复习笔记--期末

    2024-01-06 10:52:05       56 阅读
  4. vs2019+qt+opencv+open3d

    2024-01-06 10:52:05       54 阅读