简单实现一下倒计时功能
事情的起因是产品在追加需求的时候突然提了一个倒计时的功能。很简单 60s。
本来是想使用 element 的 “Statistic 统计数值” 这个组件来实现的。上线前的追加需求嘛。当然是越快越好。于是一番引入过后发现...版本不支持。没办法,只能自己手动写了。
ps: 还被老大问了这么基础的面试题你不会做吗。我会做但是没做过!
简单粗暴的实现 60s 倒计时功能:
export default {
props: {
visible: Boolean
},
data() {
return {
langs: {
notice: ['提示', 'Notice'],
wait: ['等待', 'Wait'],
},
dateNum: 60,
}
},
watch: {
visible(v) {
if(!v) {
clearInterval(timer)
this.dateNum = 60
return
}
const now = new Date()
const deadline = Date.parse(now) + 60000
timer = setInterval(() => {
const nowDate = Date.parse(new Date())
this.dateNum = (deadline - nowDate) / 1000
if(this.dateNum < 0) {
clearInterval(timer)
}
}, 1000)
},
dateNum(v) {
if(v === 0) {
this.$emit('close')
}
}
},
beforeDestroy() {
clearInterval(timer)
},
render() {
return <el-dialog
title={this.$tt('notice')}
visible={this.visible}
append-to-body={true}
close-on-click-modal={false}
center
custom-class="custom-dialog"
width="480px"
show-close={false}
>
<div class="content">
<i class="el-icon-warning"></i>
<p>{this.$t('adsource.gam_auth_loading_message_info')}</p>
</div>
<div class="date-num" slot="footer">
{
this.$tt('wait') + " " + this.dateNum.toFixed(0) + 's'
}
</div>
</el-dialog>
}
}
使用的 element 的dialog的弹框。由于父组件用的是模版写法。所以需要在watch 里面去触发60s倒计时
踩坑点
之前对于时间格式使用的是new Date().valueOf() 这样得到的时间戳是包含毫秒的。而我的倒计时不需要显示毫秒。所有换成 Date.parse() 对于需要显示毫秒单位的需求的话可以使用 valueOf()