利用时间戳配合定时器实现倒计时效果
效果图:
image.png
代码:
<template>
<div>
<el-checkbox
v-model="checkedAuto"
@change="changeAuto"
>
自动刷新
</el-checkbox>
<el-link @click="useRefresh">手动刷新</el-link>
距离指定时间还有
<span v-if="!isClick">
{{textTime || getTimeDiff(指定时间戳(10000000000)}}
</span>
<span v-else>
{{textTime || getTimeDiff(指定时间戳(10000000000)}}
</span>
</div>
</template>
<script lang="ts">
export default Vue.extend({
data () {
return {
isClick:false , // 点击刷新标志
checkedAuto:false, // 自动刷新复选框标志
intervalDiff:0 , // 定时器
textTime:'' '', // 指定时间
}
},
methods:{
/**
* 自动刷新事件
*/
changeAuto(val:any) {
if (!val) {
clearInterval(this.intervalDiff) // 清空定时器 在开启
this.intervalDiff = 0
this.textTime = this.getTimeDiff(指定时间戳(10000000000)) // 传入指定时间
} else {
if(this.intervalDiff){
clearInterval(this.intervalDiff) // 清空定时器 在开启
this.intervalDiff = 0
}
// 防止首次不显示内容
this.textTime = this.getTimeDiff(指定时间戳(10000000000)) // 传入指定时间
this.intervalDiff = setInterval(() => {
this.textTime = this.getTimeDiff(指定时间戳(10000000000)) // 传入指定时间
},1000)
}
},
/**
* 手动刷新事件
*/
useRefresh ( ) {
this.isClick = !this.isClick
this.textTime = '' ''
this.checkedAuto = false
clearInterval(this.intervalDiff) // 清空定时器 在开启
this.intervalDiff = 0
},
/**
* 计算距离某个指定时间的方法
*/
getTimeDiff(dateTime: string| number){
// 指定日期时间
let EndTime = new Date(dateTime)
// 当前系统时间
let NowTime = new Date( )
let diff = EndTime.getTime() - NowTime.getTime()
let day = Math.floor(diff / 1000 / 60 / 60 / 24)
let hour = Math.floor((diff / 1000 / 60 / 60) % 24 )
let minute = Math.floor((diff / 1000 / 60) % 60 )
let second = Math.floor((diff / 1000) % 60 )
let html = `
${day}天
${this.createZero(hour)}时
${this.createZero(minute)}分
${this.createZero(second)}秒`
if (diff > 0) {
return html
} else {
return ''已经到达指定时间"
}
},
/**
*判断是否小于10 小于10补0
*/
createZero(n:number) {
if (n < 10) {
return `0${n}`
} else {
return n
}
}
}
})
<script>
网友评论