封装一个vue倒计时的组件

下面是一个简单的 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 秒的倒计时组件

你可能感兴趣的:(Web前端,vue.js,javascript,ecmascript)