el-dialog 弹窗框确认按钮防抖处理

el-dialog 弹窗确认框按钮防抖,防抖时间是根据接口返回时间确定,防止用户多次点击多次请求接口。

el-doalog   slot="footer"  使用命名插槽 更改el-dialog默认footer部分

    <div slot="footer" class="dialog-footer">
      <div>
        <el-button size="small" @click="$emit('cancel')">取消</el-button>
        <el-button 
            size="small" 
            :disabled="confirm_Flag" 
            @click="e=>{debounceMethods(e,confirmFun);$emit('confirm')}" 
            type="primary">
            提交
        </el-button>
      </div>
    </div>

debounceMethods:防抖函数

confirmFun:promise请求函数

./debounce.js
mixins 全局混入 
export default {
  data() {
    return {
      debounceTimer: null,
    }
  },
  methods: {
    /**
     * debounceMethods 请求防抖函数
     * @param {PointerEvent} event 点击事件
     * @param {Function} func promise请求函数
     * @param {...any} args 请求参数
     * @returns 
     */
    debounceMethods(event, func, ...args) {
      let context = this
      if (typeof func !== 'function') {
        throw new Error(func + ' is not a function!')
      } else if (!event instanceof PointerEvent) {
        throw new Error(event + ' is not a PointerEvent!')
      } else if (context.debounceTimer) {
        return false
      }
      const loadingElement = document.createElement('i');
      loadingElement.setAttribute('class', 'el-icon-loading')
      loadingElement.setAttribute('style', 'margin:0 10px 0 0')
      let element = event.target
      let Button = element.tagName !== 'BUTTON' ? element.parentElement.tagName === 'BUTTON' ? element.parentElement : element : element
      Button.setAttribute('disabled',true)
      const oClass =  Button.getAttribute('class')
      if (Button.tagName === 'SPAN' ) {
        Button.setAttribute('class', `table_actionend`)
      }
      element.insertBefore(loadingElement,element.childNodes[0])
      try {
        let callback = func.apply(context, args)
        if (callback instanceof Promise) {
          context.debounceTimer = callback.finally(() => { reset() })
        } else { 
          context.debounceTimer = setTimeout(() => {reset()}, 3000)
        }
      } catch (error) {
        reset()
      }
      function reset() {
        context.debounceTimer = null;
        element.removeChild(loadingElement)
        Button.removeAttribute('disabled')
        Button.setAttribute('class', `${oClass}`)
      }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值