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>

效果展示

相关推荐
css趣多多24 分钟前
一个UI内置组件el-scrollbar
前端·javascript·vue.js
-凌凌漆-33 分钟前
【vue】pinia中的值使用 v-model绑定出现[object Object]
javascript·vue.js·ecmascript
大橙子额3 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
LYFlied4 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
B站_计算机毕业设计之家4 小时前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
xjt_09016 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农6 小时前
Vue 2.3
前端·javascript·vue.js
跳动的梦想家h7 小时前
环境配置 + AI 提效双管齐下
java·vue.js·spring
Mr Xu_8 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
一 乐8 小时前
校园二手交易|基于springboot + vue校园二手交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端