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

2023-02-22,,

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>

  

vue基于 element ui 的按钮点击节流的相关教程结束。

《vue基于 element ui 的按钮点击节流.doc》

下载本文的Word格式文档,以方便收藏与打印。