传入剩余时间戳获取多个倒计时
分装方法
export function countDownFun ( time) {
let timestamp = new Date ( ) . getTime ( )
let times = time - timestamp
let playTime,
day = 0 ,
hour = 0 ,
minute = 0 ,
second = 0 ;
if ( times > 0 ) {
second = Math. floor ( times / 1000 ) ;
day = Math. floor ( second / 86400 ) ;
second = second % 86400 ;
hour = Math. floor ( second / 3600 ) ;
second %= 3600 ;
minute = Math. floor ( second / 60 ) ;
second %= 60 ;
}
if ( day <= 9 ) day = '0' + day;
if ( hour <= 9 ) hour = '0' + hour;
if ( minute <= 9 ) minute = '0' + minute;
if ( second <= 9 ) second = '0' + second;
if ( day > 0 ) {
playTime = ` ${ day} 天 ${ hour} 小时 ${ minute} 分钟 ${ second} 秒` ;
}
if ( day <= 0 && hour > 0 ) {
playTime = ` ${ hour} 小时 ${ minute} 分 ${ second} 秒` ;
}
if ( day <= 0 && hour <= 0 ) {
playTime = ` ${ minute} 分钟 ${ second} 秒` ;
}
return playTime
}
调用方法
< template>
< view>
< view v- for = "(item, index) in times" : key= "index" > { { item. currentTime } } < / view>
< / view>
< / template>
import { countDownFun } from '../../commom/times.js' ;
export default {
data ( ) {
return {
times: [
{
haveTime: '1599917668000'
} ,
{
haveTime: '1599817668000'
}
]
} ;
} ,
onLoad ( ) {
this . timer ( this . times) ;
} ,
methods: {
timer ( times) {
let that = this ;
setInterval ( ( ) => {
times. forEach ( ( item, index) => {
item. haveTime-- ;
that. $set ( item, 'currentTime' , countDownFun ( item. haveTime) ) ;
} ) ;
} , 1000 ) ;
}
}
} ;
< / script>