vue2和vue3两种倒计时CountDown实现
一、vue2
1.CountDown.vue
<template>
<span style="color: red;font-weight: 500;font-size: 16px;" :endTime="endTime">
<slot>
{{ content }}
</slot>
</span>
</template>
<script>
export default {
data() {
return {
content: '',
timer: null,
}
},
props: {
endTime: {
type: String,
default: ''
},
},
watch: {
endTime() {
this.countdown(this.endTime)
}
},
beforeUnmount() {
if (this.timer) {
clearInterval(this.timer);
}
},
mounted() {
this.countdown(this.endTime)
},
methods: {
countdown(timestamp) {
let self = this;
if (self.timer) {
clearInterval(self.timer);
}
this.timer = setInterval(function () {
let nowTime = new Date();
if (!timestamp || timestamp.length == 0) {
return
}
let endTime = new Date(timestamp * 1000);
let t = endTime.getTime() - nowTime.getTime();
if (t > 0) {
let day = Math.floor(t / 86400000);
let hour = Math.floor((t / 3600000) % 24);
let min = Math.floor((t / 60000) % 60);
let sec = Math.floor((t / 1000) % 60);
let format = '';
if (day > 0) {
format = `${day}天${hour}小时${min}分${sec}秒`;
}
if (day <= 0 && hour > 0) {
format = `${hour}小时${min}分${sec}秒`;
}
if (day <= 0 && hour <= 0) {
format = `${min}分${sec}秒`;
}
self.content = format;
} else {
clearInterval(self.timer);
self.$emit('timeout')
}
}, 1000);
}
}
}
</script>
2.效果
二、vue3
1.安装
npm install vue3-countdown --save
2.使用
<template>
<countdown :time="remainTime" format="HH:mm:ss">
<template #="{ resolved }">
<span class="countdown-item">{{ resolved.HH }}</span><span
class="timeColon">:</span>
<span class="countdown-item">{{ resolved.mm }}</span><span
class="timeColon">:</span>
<span class="countdown-item">{{ resolved.ss }}</span>
</template>
</countdown>
</template>
<script lang="ts" setup>
import Countdown from 'vue3-countdown'
const remainTime = ref<number>();
onMounted(()=>{
let nowTime = new Date();
let endTime = new Date(limitTime);// limitTime为传入的时间
remainTime.value = endTime.getTime() - nowTime.getTime();
})
</script>
<style scoped>
.countdown-item {
padding: 3px 6px;
border-radius: 3px;
color: #fff;
font-size: 16px;
background-color: #c00;
}
.timeColon {
color: #FFF;
font-weight: 500;
font-size: 16px;
margin: 0 5px;
}
</style>
3.效果