vue防连点的两种解决思路

11/4/2021 vue前端

有效防止多次点击,重复请求接口

# 1.固定时间型

# 1.1局部注册

首先定义一个preventReClick.js

export default {
    inserted(el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 3000)
            }
        })
    }
}

在需要调用的界面

<template>
  <div class="about">
<!--3.使用v-preventReClick-->
    <el-button type="primary" @click="handleLogin" v-preventReClick>登录</el-button>
  </div>
</template>

<script>
/*1.引入js*/
import preventReClick from "@/plugins/preventReClick";

export default {
  name: 'About',
  /*2.注册局部指令*/
  directives: {
    preventReClick
  },
  methods: {
    handleLogin() {
      console.log("您好" + new Date().getTime());
    }
  }
}
</script>

# 1.2全局注册

首先定义一个preventReClick.js

import Vue from 'vue'
const preventReClick = Vue.directive('preventReClick', {
    inserted: function (el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 3000)
            }
        })
    }
});
export default preventReClick

main.js中注册

import Vue from 'vue'
import preventReClick from "@/plugins/preventReClick";
Vue.use(preventReClick)

在需要的点击事件处使用v-preventReClick

<template>
  <div class="about">
    <el-button type="primary" @click="handleLogin" v-preventReClick>登录</el-button>
  </div>
</template>

# 2.异步关闭

直接参考常用的组件

https://vant-contrib.gitee.io/vant/#/zh-CN/dialog#yi-bu-guan-bi (opens new window)

https://element.eleme.cn/#/zh-CN/component/loading (opens new window)