(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);
},
示例: