创建countdown.js
// 获取倒计时
class getCountDown {
calculateTime(next_time, format, symbol) {
//获取倒计时
let nowTime = new Date()
let nextTime = new Date(next_time)
let countDownTime
if (isNaN(nextTime)) {
//兼容ios系统
nextTime = new Date(next_time.replace(/-/g, "/"))
countDownTime = nextTime.getTime() - nowTime.getTime(); //毫秒差
} else {
countDownTime = nextTime - nowTime
}
if (countDownTime <= 0) {
//倒计时不能为负
countDownTime = 0
}
//获取天数
let day = Math.floor(countDownTime / 1000 / 3600 / 24);
if (day < 0) {
day = '00'
} else {
day = day < 10 ? '0' + day : day + ''
}
//获取小时数
let hours = Math.floor(countDownTime % (3600 * 24 * 1000) / 1000 / 3600);
if (hours < 0) {
hours = '00'
} else {
hours = hours < 10 ? '0' + hours : hours + ''
}
//获取分钟数
let minutes = Math.floor(countDownTime % (3600 * 24 * 1000) / 1000 % 3600 / 60);
if (minutes < 0) {
minutes = '00'
} else {
minutes = minutes < 10 ? '0' + minutes : minutes + ''
}
//获取秒数
var seconds = Math.floor(countDownTime % (3600 * 24 * 1000) / 1000 % 3600 % 60);
if (seconds < 0) {
seconds = '00'
} else {
seconds = seconds < 10 ? '0' + seconds : seconds + ''
}
//'dhms','/'
let date_time
if (!format) {
format = 'hms'
}
if (!symbol) {
date_time = []
} else {
date_time = ''
}
let arr = format.split('')
for (let i = 0; i < arr.length; i++) {
if (!symbol) {
//无自定义符号
switch (arr[i]) {
case 'd':
date_time.push(day)
break;
case 'h':
date_time.push(hours)
break;
case 'm':
date_time.push(minutes)
break;
case 's':
date_time.push(seconds)
break;
}
} else {
// 有自定义符号
switch (arr[i]) {
case 'd':
if (i != arr.length - 1) {
date_time += day + symbol
} else {
date_time += day
}
break;
case 'h':
if (i != arr.length - 1) {
date_time += hours + symbol
} else {
date_time += hours
}
break;
case 'm':
if (i != arr.length - 1) {
date_time += minutes + symbol
} else {
date_time += minutes
}
break;
case 's':
if (i != arr.length - 1) {
date_time += seconds + symbol
} else {
date_time += seconds
}
break;
}
}
}
return date_time
}
}
// 使用方式
// import getCountDown from '@/utils/countdown.js'//引入
// getCountDown.calculateTime('2022-06-02 20:30:00', 'dhms', ':')//参数:时间 , d:天、h:小时、m:分钟、s:秒 , 间隔符号(如:':\+=')
export default new getCountDown()
在页面中使用
import getCountDown from '@/utils/countdown/countdown.js'
data(){
return{
timer: null, //计时器
timerFlag: true, //倒计时销毁表标识
time_val:'2022-08-05 11:00:00"
}
},
methods: {
// 开始获取倒计时
startCount(time_val) {
//倒计时
if (!this.timerFlag) {
//销毁倒计时
clearTimeout(this.timer)
this.timer = null
return
}
if (this.timer) {
//防止产生多个倒计时
clearTimeout(this.timer)
this.timer = null
}
this.timer = setTimeout(() => {
let timeArr = getCountDown.calculateTime(time_val, 'dhms')
this.counDownTime = timeArr
}, 1000)
},
},
beforeDestroy() {
//销毁计时器
if (this.timer) {
clearTimeout(this.timer)
this.timer = null
}
this.timerFlag = false
}
如果获取多个倒计时,就循环遍历一下