vue vue3 节流 封装全局 自定义全局 节流


前言

一、节流是什么?

"节流"是一种控制事件触发频率的技术。当某个事件被触发时,节流能够确保事件处理函数不会立即执行,而是在一定的时间间隔之后执行。这有助于减少事件处理函数的执行次数,特别是在处理频繁触发的事件(比如滚动、调整窗口大小、输入框输入等)时,以提高性能和减轻不必要的计算负担。

二、使用步骤

1.创建文件

#创建throttle.js
const throttle = (fn, delay) => {
   
  let last = 0
  return function () {
   
    const now = Date.now()
    if (now - last >= delay) {
   
      fn.apply(this, arguments)
      last = now
    }
  }
}

export default {
   
  mounted(el, binding) {
   
    const {
    value, arg } = binding
    const delay = arg ? parseInt(arg, 10) : 1000

    const throttledClick = throttle(value, delay)

    el.__throttledClick__ = throttledClick

    el.addEventListener('click', throttledClick)
  },
  beforeUnmount(el) {
   
    console.log('Before unmount')
    if (el) {
   
      console.log(el)
      console.log(el.__throttledClick__)
      el.removeEventListener('click', el.__throttledClick__)
      delete el.__throttledClick__
    }
  }
}

2.全局定义

import throttleDirective from '@/utils/throttle' // 注册全局指令
app.directive('throttle', throttleDirective)

在这里插入图片描述


3.全局使用

//这里面默认1000   可自定义时间 
	<el-button  type="primary" v-throttle="opneDialog"> 添加机构 </el-button>
	<el-button  type="primary" v-throttle:3000="opneDialog"> 添加机构 </el-button>

!!!注意事项

// 这种写法 需要把单独写为方法 才可以正常使用
   <el-button  @click="formVisible = true"> 添加机构 </el-button>

相关推荐

  1. Vue3定义全局指令

    2023-12-27 11:38:01       46 阅读
  2. SpringBoot定义全局事务

    2023-12-27 11:38:01       64 阅读
  3. Vue3全局组件和定义指令

    2023-12-27 11:38:01       64 阅读
  4. Vue将iconfont封装全局组件,定义类名

    2023-12-27 11:38:01       39 阅读
  5. Springboot定义全局异常处理

    2023-12-27 11:38:01       62 阅读

最近更新

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

    2023-12-27 11:38:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-27 11:38:01       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-27 11:38:01       87 阅读
  4. Python语言-面向对象

    2023-12-27 11:38:01       96 阅读

热门阅读

  1. KEPServerEX 6 之 GE Ethernet 连接FANUC ROBOT机器人实战

    2023-12-27 11:38:01       58 阅读
  2. 音频筑基:码率模式CBR、VBR、CVBR一文说清

    2023-12-27 11:38:01       221 阅读
  3. 7.微服务设计原则

    2023-12-27 11:38:01       58 阅读
  4. 类与对象(C++)

    2023-12-27 11:38:01       69 阅读