123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <template>
- <view class="exam-count-down-content">
- <view v-if="data.status === 'before'">
- <view class="exam-count-down-timer">{{formatTime}} </view>
- </view>
- </view>
- </template>
- <script setup>
- import {
- reactive,
- onUnmounted,
- computed,
- watch
- } from 'vue';
- const STATUS = {
- init: null,
- moreThenAnHour: 'more',
- before: 'before', // 等待参加
- after: 'after',
- };
- const props = defineProps({
- count: {
- type: Number,
- default: 10
- }
- })
- const Emits = defineEmits(['time-end'])
- const data = reactive({
- curCount: 0,
- status: STATUS.init,
- timer: null
- })
- const formatTime = computed(() => {
- if (data.curCount > 3600) {
- return '';
- }
- const minute = (Math.floor(data.curCount / 60)).toString().padStart(2, '0');
- const second = (Math.floor(data.curCount % 60)).toString().padStart(2, '0');
- return `${minute}:${second}`;
- })
- watch(() => data.curCount, (newVal) => {
- if (newVal > 3600) {
- data.status = STATUS.moreThenAnHour;
- } else if (newVal <= 3600 && newVal > 0) {
- data.status = STATUS.before;
- } else {
- data.status = STATUS.after;
- }
- }, {
- immediate: true
- })
- // 执行组件 组件启动
- function init() {
- console.log('init')
- data.curCount = props.count;
- if (data.curCount > 0) {
- countDown(data.curCount);
- }
- }
- // 终止组件 恢复初始化
- function termination() {
- clearTimer();
- resetCurCount();
- resetCurStatus();
- }
- function resetCurCount() {
- curCount = 0;
- }
- function resetCurStatus() {
- data.status = STATUS.init;
- }
- function clearTimer() {
- clearInterval(data.timer);
- data.timer = null;
- }
- // 倒计时业务执行
- function countDown(TIME_COUNT) {
- // 参数非数字 异常禁止执行
- if (typeof TIME_COUNT !== 'number') {
- return false;
- }
- // 参数小于等于0 不需要倒计时
- if (TIME_COUNT <= 0) {
- return false;
- }
- // 执行业务
- if (!data.timer) {
- data.timer = setInterval(() => {
- // 倒计时存在 执行倒计时业务
- if (data.curCount > 0) {
- data.curCount--;
- if (data.curCount <= 0) {
- Emits('time-end', true)
- data.clearTimer();
- }
- }
- }, 1000);
- }
- }
- onUnmounted(() => {
- clearTimer()
- })
-
- defineExpose({
- init,termination
- })
- </script>
- <style>
- </style>
|