Uniapp Vue 实现当前日期到给定日期的倒计时组件开发

应用场景与需求分析

在移动端应用开发中,倒计时功能是常见的交互需求,例如限时促销活动、订单超时提醒、考试倒计时等场景。本文将基于 Uniapp 框架,实现一个从当前日期到给定日期的倒计时组件,支持显示 HH:mm:ss 格式的剩余时间,并具备自动更新和资源释放机制。

实现思路

  1. 通过 props 接收目标时间字符串(如 '2024-12-31 23:59:59')
  2. 在组件挂载时启动定时器,每秒计算当前时间与目标时间的差值
  3. 使用 dayjs 的 duration 方法将时间差格式化为 HH:mm:ss
  4. 当时间差小于等于 0 时,清除定时器并显示 00:00:00
  5. 组件销毁前清除定时器,避免内存泄漏

完整代码

javascript 复制代码
<template>
  <view class="count-down">
    <text>剩余时间:{{ timeData }}</text>
  </view>
</template>
<script>
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

export default {
  props: {
    time: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      timeData: '00:00:00',
      timer: null
    }
  },
  mounted() {
    if (this.time) {
      this.updateTime()
      this.timer = setInterval(this.updateTime, 1000)
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    updateTime() {
      const diff = dayjs(this.time).diff(dayjs())
      this.timeData =
        diff > 0 ? dayjs.duration(diff).format('HH:mm:ss') : '00:00:00'
      if (diff <= 0) {
        clearInterval(this.timer)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.count-down {
  color: gold;
}
</style>

使用

javascript 复制代码
  <c-count-down :time="time"></c-count-down>

效果展示

相关推荐
滴滴答答哒17 小时前
VUE3+element-plus MultiSelect 多选下拉组件
前端·javascript·vue.js
其美杰布-富贵-李17 小时前
04 watch 与 Vue 响应式数据流
前端·javascript·vue.js
其美杰布-富贵-李20 小时前
03 ref、reactive 与 computed 响应式数据
前端·javascript·vue.js
嘟嘟071721 小时前
useRef + Web Worker:React 中的耗时计算不卡页面
javascript·vue.js
万敏21 小时前
Vue3 全栈实战第五周:Vitest 单元测试从零搭建实战记录
vue.js·node.js·全栈
sugar__salt1 天前
跟着 Demo 学 Pinia:两种仓库写法 + 完整 TodoList 复现
前端·javascript·vue.js·前端框架·vue
A24207349301 天前
Vue + TypeScript 请求数据后结合 Element UI 实现树形菜单与下拉选择
vue.js·ui·typescript
java1234_小锋1 天前
Vue3专题 - 条件渲染
前端·javascript·vue.js
鸽鸽1 天前
Vue 3 API 完全指南:从 Options 到 Composition 的进阶之路
前端·vue.js
肉肉不吃 肉1 天前
无渲染组件和组合式函数
前端·javascript·vue.js