一、组件自带
简单粗暴的先看下自己所用组件是否提供节流api,譬如为uniapp而生的u-view组件。
<template>
<div>
// uview@1x版本
<u-button :throttle-time="3000">
提交
</u-button>
// uview@2x版本
<u-button :throttleTime="3000">
提交
</u-button>
</div>
</template>
二、动态绑定组件loading或disabled
这里只列举element-ui中的el-button组件的loading。
<template>
<div>
<!-- 使用v-bind:loading绑定data选项内的btnLoading -->
<el-button :loading="btnLoading" @click="submit">
提交
</el-button>
</div>
</template>
<script>
// 模拟请求接口
import { sendMsg } from "@/api/xxx.js";
export default {
data() {
return {
btnLoading: false
}
},
methods: {
async submit() {
// 点击button按钮时,让loading动作出现,此时button是禁用点击的
this.btnLoading = true;
try {
let res = await sendMsg();
if(res && res.code == 200) {
// 在接口成功时,将loading动作取消,以达到节流效果
this.btnLoading = false;
return;
} else {
// 在接口失败时,不要忘记将loading动作取消
this.btnLoading = false;
return;
}
} catch(err) {
console.log(err);
// 接口错误时也要做相应的操作
this.btnLoading = false;
return;
};
}
}
}
</script>
三、自己写JS或方法类
这里只列举设置setTimeout定时器的方案。
<template>
<div>
<button @click="submit">
提交
</button>
</div>
</template>
<script>
// 模拟请求接口
import { sendMsg } from "@/api/xxx.js";
export default {
data() {
return {
stopClick: false,
timer: null
}
},
destroyed() {
clearTimeout(this.timer);
},
methods: {
submit() {
// 这里抓取一下this指针,防止待会儿setTimeout函数内指针找不到
let that = this;
// 如果参数为true,直接退出方法,如果为假则往下走
if(that.stopClick) {
console.log("1s之内只能点击1次");
return;
};
// 将参数设置为true,并做一些动作和设置定时器
that.stopClick = true;
that.sendMsg();
// 设置定时器,1s后才能点击
that.timer = setTimeout(() => {
that.stopClick = false;
}, 1000);
},
async sendMsg() {
try {
...
} catch(e) {
...
};
}
}
}
</script>