Vue - 倒计时组件编写
编写通用倒计时组件
显示效果如下
代码编写,父组件引入倒计时组件countDown,传入endDate
<div class="countDown">
<span>
<span class="countDownTip" v-show="showTime">距离抢购结束还有</span>
<span class="countDownColon" v-show="showTime">:</span>
<countDown :endDate="endDate"></countDown>
</span>
</div>
倒计时组件代码
接收父组件传进来的活动结束时间
发请求获取服务器时间并计算出服务器时间与用户系统时间的时间差timeSet
后续当前时间采用用户系统时间+时间差
调用countDown方法,活动结束时间与当前时间计算出时分秒,通过setTimeout实现倒计时效果
<template>
<div>
<span class="hour">{{hour}}</span>
<span class="colonfront">:</span>
<span class="min">{{min}}</span>
<span class="colonbackend">:</span>
<span class="sec">{{sec}}</span>
</div>
</template>
<script>
import Env from "../../util/env";
import axios from "../../util/Axios";
import qs from "qs";
export default {
name: "countDown",
props: ["endDate"],
data(){
return {
serverTime:'',
currentTime:'',
timeSet:'',
endDate:'',
hour:0,
min:0,
sec:0
}
},
created: function () {
},
mounted(){
let self = this;
axios.Jsonp(`这里发请求,获取服务器时间`,{
}).then(res=>{
let result = res;
self.serverTime = result.serverTime;
self.currentTime = Date.parse(result.currentTime);
//服务器时间与用户系统时间的时间差
self.timeSet = self.serverTime - Date.parse(new Date());
this.countDown();
}).catch(function (error) {
});
},
methods:{
countDown:function(){
let now = Date.parse(new Date()) + this.timeSet;
if(this.endDate<now){
return;
}
if(this.endDate>=now){
this.showTime=true;
this.notBegin=false;
this.end=false;
const msec = this.endDate - now;
let hour = parseInt(msec/1000/60/60%24);
let min = parseInt(msec/1000/60%60);
let sec = parseInt(msec/1000%60);
this.hour = hour>9 ? hour:'0'+hour;
this.min = min>9 ? min:'0'+min;
this.sec = sec>9 ? sec:'0'+sec;
const that = this;
setTimeout(function(){
that.countDown();
},1000)
}
}
}
}
</script>
<style scoped lang="scss">
@import "../../css/css/tool/function.scss";
div{
display: inline-block;
}
.hour{
width: pxrem(16px);
height: pxrem(13px);
color: #E21F25;
}
.colonfront{
width: pxrem(13px);
height: pxrem(13px);
color: #E21F25;
}
.min{
width: pxrem(16px);
height: pxrem(13px);
color: #E21F25;
}
.colonbackend{
width: pxrem(13px);
height: pxrem(13px);
color: #E21F25;
}
.sec{
width: pxrem(16px);
height: pxrem(13px);
color: #E21F25;
}
</style>