复制代码 粘贴到vue 文件 单独引入即可
<dowm-time :setTime.sync="time"></dowm-time>
修改文字样式使用 组件的 class
<template>
<div class="number-grow-warp">
<span ref="time">{{ time }}</span>
</div>
</template>
<script>
export default {
props: {
setTime: Number,
},
data() {
return {
time: 0,
timer: undefined, // 计时器,作用:组件销毁的时候需要把定时器清除
};
},
components: {},
mounted() {
// this.time = this.setTime;
this.time = this.countDown();
this.start(); // 24小时倒计时
},
methods: {
// 获取当前时间的24小时倒计时
countDown() {
//计算相差多少毫秒 未来时间.需要传参.月份"month-1" 当前时间
var minusTime = this.setTime - new Date();
//获取元素
var days = parseInt(minusTime / 86400000); //1天 = 86400000毫秒
var hours = parseInt((minusTime % 86400000) / 3600000); //1小时 = 3600000毫秒
var minutes = parseInt((minusTime % 3600000) / 60000); //1分钟 = 60000毫秒
var seconds = parseInt((minusTime % 60000) / 1000); //1秒 = 1000毫秒
//空位补零.
function checkTime(i) {
//将0-9的数字前面加上0\. 1变为01
if (i < 10&&i>=0) {
return "0" + i;
} else {
return i;
}
}
//带入函数,获取新元素
// days = checkTime(days);
// hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
clearInterval(this.timer); // 组件销毁时清除定时器
this.$emit("finish");
}
// 输出格式可自行修改
return checkTime(hours + days * 24) + ":" + minutes + ":" + seconds;
},
start() {
this.timer = setInterval(() => {
this.time = this.countDown();
}, 1000);
},
},
destroyed() {
clearInterval(this.timer); // 组件销毁时清除定时器
},
};
</script>
<style scoped>
</style>