examCountDown.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <template>
  2. <view class="exam-count-down-content">
  3. <view v-if="data.status === 'before'">
  4. <view class="exam-count-down-timer">{{formatTime}} </view>
  5. </view>
  6. </view>
  7. </template>
  8. <script setup>
  9. import {
  10. reactive,
  11. onUnmounted,
  12. computed,
  13. watch
  14. } from 'vue';
  15. const STATUS = {
  16. init: null,
  17. moreThenAnHour: 'more',
  18. before: 'before', // 等待参加
  19. after: 'after',
  20. };
  21. const props = defineProps({
  22. count: {
  23. type: Number,
  24. default: 10
  25. }
  26. })
  27. const Emits = defineEmits(['time-end'])
  28. const data = reactive({
  29. curCount: 0,
  30. status: STATUS.init,
  31. timer: null
  32. })
  33. const formatTime = computed(() => {
  34. if (data.curCount > 3600) {
  35. return '';
  36. }
  37. const minute = (Math.floor(data.curCount / 60)).toString().padStart(2, '0');
  38. const second = (Math.floor(data.curCount % 60)).toString().padStart(2, '0');
  39. return `${minute}:${second}`;
  40. })
  41. watch(() => data.curCount, (newVal) => {
  42. if (newVal > 3600) {
  43. data.status = STATUS.moreThenAnHour;
  44. } else if (newVal <= 3600 && newVal > 0) {
  45. data.status = STATUS.before;
  46. } else {
  47. data.status = STATUS.after;
  48. }
  49. }, {
  50. immediate: true
  51. })
  52. // 执行组件 组件启动
  53. function init() {
  54. data.curCount = props.count;
  55. if (data.curCount > 0) {
  56. countDown(data.curCount);
  57. }
  58. }
  59. // 终止组件 恢复初始化
  60. function termination() {
  61. clearTimer();
  62. resetCurCount();
  63. resetCurStatus();
  64. }
  65. function resetCurCount() {
  66. curCount = 0;
  67. }
  68. function resetCurStatus() {
  69. data.status = STATUS.init;
  70. }
  71. function clearTimer() {
  72. clearInterval(data.timer);
  73. data.timer = null;
  74. }
  75. // 倒计时业务执行
  76. function countDown(TIME_COUNT) {
  77. // 参数非数字 异常禁止执行
  78. if (typeof TIME_COUNT !== 'number') {
  79. return false;
  80. }
  81. // 参数小于等于0 不需要倒计时
  82. if (TIME_COUNT <= 0) {
  83. return false;
  84. }
  85. // 执行业务
  86. if (!data.timer) {
  87. data.timer = setInterval(() => {
  88. // 倒计时存在 执行倒计时业务
  89. if (data.curCount > 0) {
  90. data.curCount--;
  91. if (data.curCount <= 0) {
  92. Emits('time-end', true)
  93. data.clearTimer();
  94. }
  95. }
  96. }, 1000);
  97. }
  98. }
  99. onUnmounted(() => {
  100. clearTimer()
  101. })
  102. defineExpose({
  103. init,termination
  104. })
  105. </script>
  106. <style>
  107. </style>