现有一个按钮,如下图
点击时
再次点击
刷新窗口再次点击
刷新窗口依然可以实现点击频率控制。
代码实现:
<template>
<!--<el-config-provider :locale="locale">
<router-view/>
</el-config-provider>-->
<el-button type="primary" @click="handleClick">click</el-button>
</template>
<script setup lang="ts">
// @ts-ignore
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 国际化配置
const locale = reactive(zhCn)
const handleClick = () => {
// 间隔为30s
const delay = 30000
const key = 'ls_handle_click'
let cache = getExpiredItem(key)
if (cache <= 0) {
setExpiredItem(key, Date.now(), delay)
} else {
const now = Date.now()
const diff = delay / 1000 - (now - cache) / 1000
ElMessage({
showClose: true,
message: `点击过于频繁,请${Math.floor(diff)}秒后尝试!`,
type: 'warning',
})
return
}
// 执行按钮功能(处理业务逻辑)
handleAlert()
}
// 封装可以设置过期时间的localStorage
const setExpiredItem = (key, value, expires) => {
const data = {
value: value,
expires: Date.now() + expires
}
window.localStorage.setItem(key, JSON.stringify(data))
}
// 封装获取有过期时间的localStorage(我们规定如果key到期则返回-1,如果没有这个key就返回0)
const getExpiredItem = (key) => {
const value = window.localStorage.getItem(key)
if (!value) {
return 0
}
const data = JSON.parse(value)
if (Date.now() > data.expires) {
window.localStorage.removeItem(key)
return -1
}
return data.value
}
// 按钮功能
const handleAlert = () => {
ElMessage({
showClose: true,
message: 'this is a success message.',
type: 'success',
})
}
</script>
<style scoped lang="scss">
</style>