vue语法
简单手撸了一个倒计时,分享一下
获取谋定时间:
// 判断本地是否有目标时间,有就使用,没有就存一个目标时间,目标时间=当前时间+10天
let targetTime = localStorage.getItem("targetTime") ? localStorage.getItem("targetTime") : localStorage.setItem("targetTime", new Date().valueOf() + 864000000);
// 当目标时间距离当前时间小于1000时重置目标时间位当前时间+10天
if ((targetTime - new Date().valueOf()) < 1000) {
localStorage.setItem("targetTime", new Date().valueOf() + 864000000)
}
页面如下:
<template>
<div class='countDown'>
<div class="countDown_time">
<div class="time_box">{{ countDown.hours | zeroFilter }}</div>
<span>{{ $t('countDown.hours') }}</span>
</div>
<span>:</span>
<div class="countDown_time">
<div class="time_box">{{ countDown.mins | zeroFilter }}</div>
<span>{{ $t('countDown.minutes') }}</span>
</div>
<span>:</span>
<div class="countDown_time">
<div class="time_box">{{ countDown.sec | zeroFilter }}</div>
<span>{{ $t('countDown.secons') }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'CountDown',
data() {
return {
countDown: {
days: 0,
hours: 0,
mins: 0,
sec: 0,
},
timer: null
}
},
mounted() {
clearInterval(this.timer);
this.timer = setInterval(() => {
let targetTime = localStorage.getItem("targetTime")
let nowTime = new Date().valueOf();
let t = targetTime - nowTime;
if (t <= 1000) {
localStorage.setItem("targetTime", new Date().valueOf() + 864000000);
}
this.countDown.days = Math.floor(t / 86400000);
this.countDown.hours = Math.floor((t / 3600000) % 24);
this.countDown.mins = Math.floor((t / 60000) % 60);
this.countDown.sec = Math.floor((t / 1000) % 60);
}, 1000);
},
filters: {
zeroFilter(value) {
if (value < 10) {
return '0' + value;
} else {
return value
}
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style lang='scss' scoped>
@import "@/assets/style/components/countDown.scss";
</style>
scss文件:
.countDown {
@include flex(left);
padding: 20px 0px;
box-sizing: border-box;
.countDown_time{
width: 60px;
height: 60px;
text-align: center;
background: rgba(255,255,255,0.1);
.time_box{
width: 60px;
height: 60px;
border-radius: 8px;
font-size: 30px;
font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
font-weight: bold;
background: rgba(255,255,255,0.1);
color: #FFFFFF;
line-height: 60px;
text-align: center;
}
span{
font-size: 12px;
font-family: MicrosoftYaHei;
color: rgba(255,255,255,0.7);
line-height: 16px;
}
}
& > span {
width: 30px;
text-align: center;
font-size: 30px;
font-weight: bold;
color: #5933ff;
line-height: 60px;
}
}
注意:@include flex(left);为封装的全局方法
@mixin flex($justify:center, $align:center, $direction:row, $display:flex, $wrap:nowrap) {
display: $display;
flex-wrap: $wrap;
flex-direction: $direction;
align-items: $align;
justify-content: $justify;
}
分享结束 下一期再见 beibie~