封装一个vue倒计时的组件

该示例展示了如何在Vue中创建一个倒计时组件,组件接收duration属性来设定秒数,并在mounted阶段启动倒计时,每秒更新remainingTime,当时间到0时自动停止。beforeDestroy钩子用于清除定时器,确保资源释放。

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

下面是一个简单的 Vue 倒计时组件的示例:
<template>
  <div>
    <p>倒计时: {{ remainingTime }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      remainingTime: 0,
      intervalId: null
    };
  },
  props: {
    duration: {
      type: Number,
      required: true
    }
  },
  mounted() {
    this.startCountdown();
  },
  methods: {
    startCountdown() {
      this.remainingTime = this.duration;
      this.intervalId = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--;
        } else {
          clearInterval(this.intervalId);
        }
      }, 1000);
    }
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  }
};
</script>
使用示例
<template>
  <div>
    <Countdown :duration="60" />
  </div>
</template>

<script>
import Countdown from '@/components/Countdown.vue';

export default {
  components: {
    Countdown
  }
};
</script>

在上述示例中,Countdown 组件接受一个 duration 属性,表示倒计时的总时长(以秒为单位)。组件在 mounted 钩子函数中启动倒计时,并使用 setInterval 每秒更新 remainingTime 的值,直到倒计时结束。在组件销毁之前使用 beforeDestroy 钩子函数清除 intervalId。

在父组件中使用 即可创建一个倒计时为 60 秒的倒计时组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值