Vue mall countdown hour minute second unit

 This is  the code inside the template tag

<div id="app">
  <h1>倒计时:{
   
   { hours }}小时 {
   
   { minutes }}分钟 {
   
   { seconds }}秒</h1>
</div>

This is the code in 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>

Here's what it looks like:

Guess you like

Origin blog.csdn.net/Guanchong333/article/details/130246658