zoukankan      html  css  js  c++  java
  • vue基于 element ui 的按钮点击节流

    vue的按钮点击节流

    场景:

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

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

    3、弹幕不能频繁的发

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

    主要使用到了 vue的

    $listeners  $attrs
     

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

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

    详细代码如下:

    <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>
    

      

      

    使用:

    <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>
    

      

  • 相关阅读:
    对于CD翻录的一些记录
    暑期实践
    暑期实践
    垃圾处理器-CMS
    离合器半联动点的判断和技巧
    Win10+VS2019+OpenCV环境配置
    C++ 学习资料
    科目二起步原理
    道路交通安全违法行为记分分值分类总结
    NWERC 2020 题解
  • 原文地址:https://www.cnblogs.com/muamaker/p/11560162.html
Copyright © 2011-2022 走看看