按钮防重复点击方案

推荐 防抖+全局请求Loading,能够拦截99%的重复点击场景

防抖:

<script>
import { debounce } from '@/utils/throttle-debounce'

export default {
  data() {
    return {
      // maybe有更好的声明位置
      submitForm: debounce(500, this.submitFn)
    }
  },
  methods: {
    submitFn(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) {
          this.$message.warning(this.$store.state.app.checkMsg)
          return false
        }
        let params = {
          dtoList: this.ruleForm.dtoList
        }
        const requestFn = addList
        const res = await requestFn(params)
        if (res.code != 0) {
          return
        }
        this.$message.success('操作成功!')
        this.openDialogPromise.resolve()
        this.closeDialog()
      })
    }
  }
}
</script>

全局请求Loading
http.js

import axios from 'axios'
import { Message, Loading } from 'element-ui'
import router from '@/router'

//loading对象
let loadingObj = ''
//当前正在请求的数量
let needLoadingRequestCount = 0

//显示loading
function showLoading(target) {
  if (needLoadingRequestCount === 0) {
    loadingObj = Loading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
      target: target || '.app-main'
    })
  }
  needLoadingRequestCount++
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) //做个保护

  if (needLoadingRequestCount === 0 && loadingObj) {
    loadingObj.close()
    loadingObj = null
  }
}

// create an axios instance
const service = axios.create({
  baseURL: '',
  withCredentials: true,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Application-Token': '',
    projectId: ''
  }
})

/* 请求前拦截器 */
service.interceptors.request.use(
  (config) => {
    let customConfig = config['config']

    if (!customConfig.notLoading) {
      showLoading(customConfig.loadingTarget)
    }

    return config
  },
  (error) => {
    hideLoading()
    return Promise.reject(error.request)
  }
)

/* http响应拦截器 */
service.interceptors.response.use(
  (response) => {
    const res = response.data

    if (response.config['config'].notLoading !== true) {
      hideLoading()
    }

    return res
  },
  (error) => {
    hideLoading()
    return Promise.reject(error.message)
  }
)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值