大家都知道,函数节流(throttle)是 JS 中一个非常常见的优化手段,可以有效的避免函数过于频繁的执行。但是,我今天确新学了一招CSS实现点击节流,分享给大家~
1. 实现背景
基于el-button封装的一个按钮组件,用法同Element。
2. 实现原理
通过CSS,点击后设置N秒禁止点击的动画。
3. 优点
无需变量控制按钮状态,开箱即用。
4. 代码实现
<template>
<el-button :class="{throttle: firstAddThrottle}" :circle="circle" :disabled="disabled" :icon="icon" :loading="loading" :plain="plain" :round="round" :size="size" :type="type"
:style="cssVars" class="my-button" @click="handleClick"
>
<slot></slot>
</el-button>
</template>
<script>
export default {
name: 'Button',
props: {
// 尺寸 medium / small / mini
size: {
type: String,
default: ''
},
// 类型 primary / success / warning / danger / info / text
type: {
type: String,
default: ''
},
// 是否朴素按钮
plain: {
type: Boolean,
default: false
},
// 是否圆角按钮
round: {
type: Boolean,
default: false
},
// 是否圆形按钮
circle: {
type: Boolean,
default: false
},
// 是否禁用状态
disabled: {
type: Boolean,
default: false
},
// 是否加载中状态
loading: {
type: Boolean,
default: false
},
// 图标类名
icon: {
type: String,
default: ''
},
// 节流秒
second: {
type: Number,
default: 5
}
},
computed: {
cssVars() {
return {
'--throttleNum': this.second + 's'
}
}
},
data() {
return {
// 第一次点击的后添加节流,后面不需要了
firstAddThrottle: false
}
},
methods: {
handleClick() {
this.firstAddThrottle = true
this.$emit('click')
}
}
}
</script>
<style lang="scss" scoped>
button {
cursor: pointer;
}
.throttle {
animation: throttle var(--throttleNum) step-end forwards;
}
button:active {
animation: none;
}
@keyframes throttle {
from {
pointer-events: none;
}
to {
pointer-events: all;
}
}
</style>
5. 使用方式
- 引入组件(全局或局部引入)
- 使用
<Button icon="el-icon-download" :second="3" size="mini" type="warning" @click="exportClick">导出</Button >