一、组件自带
简单粗暴的先看下自己所用组件是否提供节流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或方法类
3.1、节流
<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() {
// 如果参数为true,直接退出方法,如果为假则往下走
if(this.stopClick) {
console.log("1s之内只能点击1次");
return;
};
// 将参数设置为true
this.stopClick = true;
// 设置定时器,1s后才能点击
this.timer = setTimeout(() => {
this.stopClick = false;
}, 1000);
// 做一些请求或其他业务逻辑
this.sendMsg();
},
async sendMsg() {
try {
...
} catch(e) {
...
};
}
}
}
</script>
3.2、防抖
<template>
<div>
<van-button
:loading="bindBtnLoading"
@click.stop="handleClick"
>
<span>绑定新学生</span>
</van-button>
</div>
</template>
<script>
data() {
return {
bindBtnLoading: false,
timer: null
}
},
method: {
handleClick() {
this.bindBtnLoading = true
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
this.getData()
}, 300)
},
async getData() {
try {
cosnt res = await getxxx()
if (!res) {
this.bindBtnLoding = false
// ...
return
}
this.bindBtnLoding = false
// ...
return
} catch(e) {
this.bindBtnLoding = false
// ...
}
}
}
</script>