vue项目使用自定义指令v-debounce处理按钮防抖

337 阅读1分钟

背景:我们项目里面经常会有提交保存按钮,如果没有控制按钮防抖,会导致连续双击或者连续点了好几下提交保存按钮,这时候重复调用了后端的接口,导致后端出现重复的数据;

下面是自己在项目中实际使用的解决按钮防抖的处理

添加自定义指令debounce.js

import _debounce from 'lodash/debounce'
// 这里直接使用lodash库里面的debounce防抖方法,较为方便
// 也可以通过手写防抖函数来处理
let fn = null
const debounce = {
  inserted: function(el, binding) {
    fn = _debounce(binding.value, 2000, {
      leading: true,
      trailing: false
    })
    el.addEventListener('click', fn)
  },
  unbind: function(el) {
    fn && el.removeEventListener('click', fn)
  }
}
export default debounce;

lodash.png

注册v-debounce指令

index.js

import debounce from './debounce'

const install = function(Vue) {
  Vue.directive('debounce', debounce)
}

if (window.Vue) {
  window['debounce'] = debounce
  Vue.use(install); // eslint-disable-line
}

debounce.install = install
export default debounce

结构如下:

debounce.png

在需要防抖处理的按钮上使用:

<el-button
  type="primary"
  v-debounce="save"
  :loading="loadingSubmit"
  v-if="!behaviorDetail"
  >确 定</el-button
>

// 这里以elementui的按钮为例
// 原本的写法
<el-button
  type="primary"
  onclick="save"
  :loading="loadingSubmit"
  v-if="!behaviorDetail"
  >确 定</el-button
>
改成防抖的处理
<el-button
  type="primary"
  v-debounce="save"
  :loading="loadingSubmit"
  v-if="!behaviorDetail"
  >确 定</el-button
>