代码改变世界

vue基于 element ui 的按钮点击节流

  muamaker  阅读(5490)  评论(1编辑  收藏  举报

vue的按钮点击节流

场景:

1、在实际使用中,当我们填写表单,点击按钮提交的时候,当接口没返回之前,迅速的点击几次,就会造成多次提交。

2、获取验证码,不频繁的获取。

3、弹幕不能频繁的发

基于这几个场景,对 element-ui 的按钮进行扩展 节流

主要使用到了 vue的

$listeners  $attrs
 

$listeners:子组件里面,获取父组件对子组件 v-on 的所有监听事件

$attrs: 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

 

详细代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
    <el-button v-bind="$attrs" v-on="evet" :disabled="disabled"><slot></slot></el-button>
</template>
<script>
export default {
    name:"throat-btn",
    computed:{
        evet(){
            if(this.$listeners.click ){
                this.$listeners.click = this.throat("click");
            }
            return  this.$listeners;
        },
        disabled(){
            if(this.timer){
                return true;
            }else{
                return false;
            }
        }
    },
    data(){
        return {
            timer:null
        }
    },
    methods:{
        throat(method){
            const me = this;
            return (...args)=>{
                if(!me.timer){
                    me.$emit(method,...args);
                    me.timer = setTimeout(() => {
                        me.timer = null;
                    }, me.$attrs.throat || 5000); //默认5s的,节流
                }else{
                    me.$emit("droped",...args); //点击太频繁的事件提示
                }
            }
        }
    }
}
</script>

  

  

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
  <div class="home">
 
    <throatButton @click="customClick"  :throat="5000" >默认按钮</throatButton>
    <throatButton type="primary" @click="customClick">主要按钮</throatButton>
    <throatButton type="success" disabled>成功按钮</throatButton>
    <throatButton type="info" disabled>信息按钮</throatButton>
    <throatButton type="warning" disabled>警告按钮</throatButton>
    <throatButton type="danger" disabled>危险按钮</throatButton>
  </div>
</template>
 
<script>
// @ is an alias to /src
import throatButton from "@/components/throat-button.vue";
export default {
  name: 'home',
  components: {
    throatButton
  },
  mounted(){
    
  },
  methods:{
    customClick(e){
      console.log("----------customClick----------",e);
    },
    onchange(e){
      console.log("------onchange-------------",e);
    }
  }
}
</script>

  

 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示