vue实现倒计时

主要思路为:
将结束时间与获取当前时间做差,再通过转换时间戳为时间,使用$set修改data中的time。并添加一些结束条件和触发条件。

data(){
	return{
	  timeOver: false, // 倒计时结束标识
      endTime: '2020-05-08 23:29:29', // 结束时间
      time: {}
	}
}created(){
	let that = this
    that.timeDown()
},
methods:{
	timeDown () {
      var that = this
      if ((new Date(that.endTime)) - (new Date()) < 0) {
        return
      }
      var interval = setInterval(function trans() {
        var date = (new Date(that.endTime)) - (new Date())
        if (date <= 0) {
          that.timeOver = true
          clearInterval(interval)
        } else {
          that.$set(that.time, 'd', parseInt(date / 1000 / 60 / 60 / 24, 10))
          that.$set(that.time, 'h', parseInt(date / 1000 / 60 / 60 % 24, 10))
          if (that.time.h < 10) {
            that.$set(that.time, 'h', '0' + that.time.h)
          }
          that.time.m = parseInt(date / 1000 / 60 % 60, 10)
          if (that.time.m < 10) {
            that.$set(that.time, 'm', '0' + that.time.m)
          }
          that.time.s = parseInt(date / 1000 % 60, 10)
          if (that.time.s < 10) {
            that.$set(that.time, 's', '0' + that.time.s)
          }
        }
      }, 1000)
    },
}

猜你喜欢

转载自blog.csdn.net/weixin_44296432/article/details/106002117