可直接使用
<template>
<div :style="config.style">{{ lastTime }}</div>
</template>
<script>
const addZero = function(num) {
return num < 10 ? "0" + num : String(num);
};
export default {
props: {
config: {
type: Object,
required: true,
default: () => ({})
}
},
data() {
return {
timeStamp: 0,
curTimeStamp: "",
endTimeStamp: "",
lastTime: "",
lastTimeStamp: "",
interval: -1
};
},
methods: {
pause() {
clearInterval(this.interval);
},
reStart() {
this.curTimeStamp = Date.now();
this.endTimeStamp = this.curTimeStamp + this.lastTimeStamp;
this.startCountDown();
},
countDownInit() {
this.timeStamp = this.config.time * 60 * 1000;
this.curTimeStamp = Date.now();
this.endTimeStamp = this.curTimeStamp + this.timeStamp;
this.lastTime = this.formatTimeStamp(this.timeStamp);
this.startCountDown();
},
startCountDown() {
this.interval = setInterval(_ => {
this.lastTimeStamp = this.endTimeStamp - Date.now();
if (this.lastTimeStamp > 0) {
this.lastTime = this.formatTimeStamp(this.lastTimeStamp);
} else {
clearInterval(this.interval);
this.lastTime = "00:00:00";
this.$emit("timeEnd");
}
}, 1000);
},
formatTimeStamp(time) {
let timeDate = new Date(time);
return `${addZero(timeDate.getUTCHours())}:${addZero(
timeDate.getUTCMinutes()
)}:${addZero(timeDate.getUTCSeconds())}`;
},
validateConfig() {
if (!this.config.time) {
this.time = "00:00:00";
return false;
}
if (typeof this.config.time !== "number") {
alert("config.time format should be a number");
return false;
}
return true;
}
},
created() {
const valid = this.validateConfig();
if (valid) {
this.countDownInit();
}
}
};
</script>
<style>
</style>
|