当前位置:首页 > VUE

vue实现倒计时抢券

2026-01-12 08:25:04VUE

实现思路

通过 Vue 的响应式数据绑定和定时器功能,结合计算属性动态展示倒计时剩余时间,并在倒计时结束后触发抢券逻辑。

vue实现倒计时抢券

核心代码实现

<template>
  <div>
    <button @click="startCountdown" :disabled="isDisabled">
      {{ buttonText }}
    </button>
    <p v-if="timeLeft > 0">剩余时间: {{ formattedTime }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      timeLeft: 10, // 倒计时总秒数(示例为10秒)
      timer: null,
      isCounting: false
    };
  },
  computed: {
    formattedTime() {
      const minutes = Math.floor(this.timeLeft / 60);
      const seconds = this.timeLeft % 60;
      return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    },
    isDisabled() {
      return this.timeLeft > 0 || this.isCounting;
    },
    buttonText() {
      return this.timeLeft > 0 ? '抢券倒计时' : '立即抢券';
    }
  },
  methods: {
    startCountdown() {
      if (this.timeLeft <= 0) {
        this.handleGrabCoupon();
        return;
      }
      this.isCounting = true;
      this.timer = setInterval(() => {
        this.timeLeft--;
        if (this.timeLeft <= 0) {
          clearInterval(this.timer);
          this.isCounting = false;
        }
      }, 1000);
    },
    handleGrabCoupon() {
      // 实际抢券逻辑(如调用API)
      alert('抢券成功!');
    }
  },
  beforeDestroy() {
    clearInterval(this.timer); // 清除定时器避免内存泄漏
  }
};
</script>

关键点说明

  • 定时器管理:通过 setInterval 实现倒计时,组件销毁时需清除定时器。
  • 响应式更新:利用 computed 动态计算剩余时间的格式化显示(分钟:秒)。
  • 状态控制isDisabled 控制按钮禁用状态,避免重复触发。

优化方向

  1. 本地存储恢复:通过 localStorage 保存倒计时状态,刷新页面后继续倒计时。
  2. 服务端同步:从接口获取剩余时间,避免客户端时间误差。
  3. 动画效果:添加 CSS 动画增强交互体验。

完整示例扩展

// 本地存储恢复示例
created() {
  const savedTime = localStorage.getItem('couponTime');
  if (savedTime && savedTime > 0) {
    this.timeLeft = savedTime;
    this.startCountdown();
  }
},
watch: {
  timeLeft(newVal) {
    localStorage.setItem('couponTime', newVal);
  }
}

标签: 倒计时vue
分享给朋友:

相关文章

简易实现vue

简易实现vue

简易 Vue 实现思路 核心是数据劫持结合发布-订阅模式,通过 Object.defineProperty 或 Proxy 监听数据变化,触发视图更新。 数据劫持实现 class Observe…

vue 实现菜单

vue 实现菜单

Vue 实现菜单的方法 使用 Vue 实现菜单可以通过多种方式,以下是几种常见的方法: 使用 Vue Router 实现动态路由菜单 通过 Vue Router 可以动态生成菜单,根据路由配置自动渲…

简单实现vue

简单实现vue

Vue 的基本实现 创建一个简单的 Vue 应用需要引入 Vue 库,并编写基本的模板和数据绑定逻辑。 <!DOCTYPE html> <html lang="en"> &l…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…