这是 template 标签里面的代码
<div id="app">
<h1>倒计时:{{ hours }}小时 {{ minutes }}分钟 {{ seconds }}秒</h1>
</div>
这是js 里面的代码
<script>
export default {
data() {
return {
targetTime: new Date("2023-4-19 20:30:59").getTime(),
hours: "",
minutes: "",
seconds: "",
};
},
mounted() {
this.startCountdown();
},
methods: {
startCountdown() {
setInterval(() => {
const now = new Date().getTime();
const distance = this.targetTime - now;
// 计算剩余时间并格式化为时分秒
this.hours = Math.floor(distance / (1000 * 60 * 60));
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
this.seconds = Math.floor((distance % (1000 * 60)) / 1000);
// 将单个数字转换为两位数的字符串格式
this.hours = this.formatNumber(this.hours);
this.minutes = this.formatNumber(this.minutes);
this.seconds = this.formatNumber(this.seconds);
}, 1000);
},
formatNumber(num) {
return num < 10 ? `0${num}` : `${num}`;
}
}
};
</script>
下面看看长什么样吧: