Vue 商城倒计时 时分秒 单位

这段代码展示了如何在Vue.js应用中创建一个倒计时器,目标时间设定为2023年4月19日20:30:59。通过JavaScript的setInterval方法更新剩余的小时、分钟和秒数,并使用formatNumber函数确保显示为两位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 这是 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>

下面看看长什么样吧:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值