<template>
<div
class="count-down"
@click="clickTrigger"
:class="trigger ? 'forbidden' : ''"
>
{{ trigger ? defaultSecond + 's' : text }}
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue';
const defaultProps = defineProps({
second: {
type: Number,
default: 10,
},
});
const state = reactive({
trigger: false,
timer: null,
defaultSecond: 60,
text: '获取验证码',
});
const clickTrigger = () => {
if (state.timer) return;
state.defaultSecond = defaultProps.second;
state.text = `${state.defaultSecond}S`;
state.timer = setInterval(() => {
state.defaultSecond--;
state.text = `${state.defaultSecond}S`;
if (state.defaultSecond <= 0) {
clearInterval(state.timer);
state.timer = null;
state.text = '重新获取验证码';
}
}, 1000);
};
const { timer, defaultSecond, trigger, text } = toRefs(state);
</script>
<style lang="scss" scoped>
.count-down {
min-width: 120px;
height: 30px;
padding: 10px 5px;
background-color: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 2px;
color: #333;
font-size: 14px;
}
.forbidden {
pointer-events: none;
color: #999;
}
</style>
vue3封装倒计时组件
最新推荐文章于 2024-09-07 10:11:54 发布