countDown.vue 2.09 KB
<!-- 倒计时 -->
<template>
  <div class="count-down">
    <img class="error-circle" src="../../images/error-circle.png" />
    {{ countdown }}
  </div>
</template>
<script>
export default {
  data() {
    return {
      countdown: "",
      isOvertime: false
    }
  },
  mounted() {
    this.startCountdown()
  },
  methods: {
    startCountdown() {
      const now = new Date()
      const wednesday = new Date(now)

      // 计算本周三的日期
      const day = now.getDay()
      const diff = (day - 3 + 7) % 7 // 3代表星期三
      wednesday.setDate(wednesday.getDate() - diff)
      wednesday.setHours(23, 59, 59, 0)

      // 如果今天是周四或周五
      if (day === 4 || day === 5) {
        this.isOvertime = true
        this.countdown = "已超出本周配课时间,学员需本周日前完成学习"
        return
      }

      // 如果已过本周三,显示下周三
      if (now > wednesday) {
        wednesday.setDate(wednesday.getDate() + 7)
      }

      // 开始倒计时
      this.updateCountdown(wednesday)
    },
    updateCountdown(endTime) {
      const now = new Date()

      if (now >= endTime) {
        this.isOvertime = true
        this.countdown = "已超出本周配课时间,学员需本周日前完成学习"
        return
      }

      const diff = endTime - now
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff / (1000 * 60 * 60)) % 24)
      const minutes = Math.floor((diff / (1000 * 60)) % 60)
      const seconds = Math.floor((diff / 1000) % 60)

      this.countdown = `倒计时:完成本周课程配置还剩 ${days}天${hours}时${minutes}分${seconds}秒`

      setTimeout(() => this.updateCountdown(endTime), 1000)
    }
  }
}
</script>
<style>
.count-down {
  margin-left: 20px;
  display: flex;
  align-items: center;
  width: 376px;
  height: 32px;
  border-radius: 2px;
  opacity: 1;
  background: #f47f131a;
  padding: 6px 11px;
  box-sizing: border-box;
  color: #666666;
  font-size: 12px;
  font-weight: 400;
  .error-circle {
    width: 14px;
    height: 14px;
    margin-right: 8px;
  }
}
</style>