vue 根据时间类型进行倒计时

(PS:这两个方法是写在methods里的哦!)

确定传过来的时间数据类型

    datetime: function(time) {
    //传过来的时间time可以是分钟数,也可以是时间戳
    //获取当前时间
      let newdate = new Date();
    //当前时间从1970.1.1到现在的毫秒数
      this.timenow = newdate.getTime();
    //判断时间类型给结束时间赋值
      if (typeof time == "number") {
        this.timeend = this.timenow + time * 60 * 1000;
      } else if (typeof time == "string") {
        this.timeend = new Date(time).getTime();
      } else {
        alert("请输入正确时间");
      }
    }

倒计时

countdown: function() {
      //定义this指向
      const that = this;
	  //设置结束时间
      const end = that.timeend;
	  //设置开始时间
      const now = new Date().getTime();

      // 做判断当倒计时结束时都为0
      if (now >= end) {
        that.day = 0;
        that.hr = 0;
        that.min = 0;
        that.sec = 0;
        return;
      }
      // 用结束时间减去当前时间获得倒计时时间戳
      const msec = end - now;
      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); //算出秒数
      //给数据赋值
      that.day = day;
      that.hr = hr > 9 ? hr : "0" + hr;
      that.min = min > 9 ? min : "0" + min;
      that.sec = sec > 9 ? sec : "0" + sec;
     
      //使用定时器 然后使用递归 让每一次函数能调用自己达到倒计时效果
      setTimeout(function() {
        that.countdown();
      }, 1000);
    },

示例:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值