作者:就是!有梦想 | 来源:互联网 | 2023-09-25 21:55
一、创建countDown.vue(倒计时组件):
<template>
<span :endTime="endTime" :endText="endText">
<slot>{{content}}</slot>
</span>
</template>
<script>
export default {
data(){
return {
content: '',
}
},
props:{//接收父组件的数据
endTime:{type:String,default:''},
endText:{type:String,default:'活动已结束'},
},
watch: {//监听时间的变化
endTime() {
this.countdowm(this.endTime)
}
},
mounted () {
this.countdowm(this.endTime)
},
methods: {
countdowm(timestamp){
let self = this;
let timer = setInterval(function(){
let nowTime = new Date();
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);
hour = hour < 10 ? "0" + hour : hour;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
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(timer);
self.content = self.endText;
}
},1000);
}
}
}
</script>
二、vue倒计时组件的使用方法(父组件里面):
<template>
<count-down :endTime="endTime" :endText="endText " />
</template>
<script>
import countDown from '@/components/countDown'//引入路径,可更改
export default {
data() {
return{
endTime:new Date("2022/04/18 08:00:20").getTime() / 1000 + ' ',
// console.log(endTime)=>得到毫秒 1658030420 可在方法里面放入后台数据,new Date('放后台数据').getTime() / 1000 + ' ',但要记得调用方法
endText:'',
}
},
components: {
countDown
},
}
</script>
说明一下:
1)endTime是一个时间戳,而且是字符串数据类型,需要处理下
let endTime = new Date("2022/04/18 08:00:20").getTime() / 1000 + ' '
2)endText是倒计时结束显示的内容
三、vue倒计时组件效果如下: