欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > Uniapp Vue 实现当前日期到给定日期的倒计时组件开发

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

2025/9/10 14:28:49 来源:https://blog.csdn.net/weixin_44185995/article/details/147141982  浏览:    关键词: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. 组件销毁前清除定时器,避免内存泄漏

完整代码

<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>

使用

  <c-count-down :time="time"></c-count-down>

效果展示

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词