vue实现时间倒计时

我们在做项目时会有很多实现时间倒计时的需求,今天正好不忙,在这里简单的封装一个时间倒计时的方法(一小时倒计时)

// html
<div>还剩{{min}}:{{sec}}获取脑力</div>

data(){
   return {
       day: 0,
       hr: 0,
       min: 0,
       sec: 0,
   }
},
mounted(){
    this.countdown()
},
countdown() {
            const end = (app.globalData.currenergy_ts + (1*60*60))*1000;  // 定义开始时间且延长1小时
            const now = Date.parse(new Date());  // 获取本地时间
           
            const msec = end - now;
            // 将时间戳进行格式化00:00的形式
            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(hr ==0 && min ==0 && sec==0){
                let n =app.globalData.currenergy+1;
                this.recoverEnergy('recover',n);
                return
            }else {
                setTimeout(function () {
                    that.countdown()
                }, 1000)
            }

        }

“It is better to be clear than to be clever.”——“做的清晰比做的聪明更好。”

你可能感兴趣的:(vue实现时间倒计时)