vue-实现倒计时功能

  • 模板
<div id="app">{{ `${day}天 ${hr}小时 ${min}分钟 ${sec}分钟` }}</div>
  • 数据
data() {
    return {
      day: 0,
      hr: 0,
      min: 0,
      sec: 0,
    }
},

mounted() {
    this.countdown()
},

methods: {
    // 倒计时方法
    countdown() {
      // 目标日期时间戳
      const end = Date.parse(new Date('2022-08-24 03:59:23'))
      // 当前时间戳
      const now = Date.parse(new Date())
      // 相差的毫秒数
      const msec = end - now

      //   console.log(msec)
      if (msec < 0) return

      // 计算时分秒数
      let day = parseInt(msec / 1000 / 60 / 60 / 24)
      let hr = parseInt((msec / 1000 / 60 / 60) % 24)
      let min = parseInt((msec / 1000 / 60) % 60)
      let sec = parseInt((msec / 1000) % 60)
      // 个位数前补零
      this.day = day
      this.hr = hr > 9 ? hr : '0' + hr
      this.min = min > 9 ? min : '0' + min
      this.sec = sec > 9 ? sec : '0' + sec
      // 赋值
      const that = this
      if (min >= 0 && sec >= 0) {
        //倒计时结束关闭订单
        if (min == 0 && sec == 0) {
          return
        }
        // 一秒后递归
        setTimeout(function () {
          that.countdown()
        }, 1000)
      }
    },
},
posted @ 2022-08-28 22:02  天使阿丽塔  阅读(797)  评论(0编辑  收藏  举报