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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM