使用 UniApp 制作倒计时与提醒功能
前言
倒计时与提醒功能在移动应用中应用广泛,如活动秒杀、任务提醒、考试倒计时等。一个实用的倒计时组件不仅要精准计时,还要兼容多端,尤其是在鸿蒙(HarmonyOS)等新兴平台上保证流畅与可靠。本文将以 UniApp 为例,详细讲解如何开发一个通用的倒计时与提醒功能组件,并结合鸿蒙平台的适配与优化建议。
一、需求与设计思路
1. 需求分析
- 支持自定义倒计时时长与格式
- 倒计时结束自动触发提醒
- 支持页面/应用切换时倒计时不中断
- 兼容鸿蒙平台,适配不同设备
- 可扩展性强,便于集成到不同业务场景
2. 设计思路
- 使用
setInterval
实现定时更新,结合Date.now()
保证精度 - 组件内部维护剩余时间,支持自定义回调
- 页面切换时保存剩余时间,返回时自动恢复
- 提供提醒回调,可结合本地通知API
- 适配鸿蒙平台的生命周期与通知能力
二、核心代码实现
1. 倒计时组件结构
vue
<template>
<view class="countdown">
<text>{{ timeStr }}</text>
</view>
</template>
2. 脚本逻辑
js
<script>
export default {
name: 'Countdown',
props: {
duration: { type: Number, required: true }, // 秒
format: { type: String, default: 'HH:mm:ss' },
onFinish: { type: Function, default: null },
},
data() {
return {
remain: this.duration,
timer: null,
timeStr: '',
endTime: Date.now() + this.duration * 1000,
};
},
methods: {
start() {
this.clear();
this.endTime = Date.now() + this.remain * 1000;
this.update();
this.timer = setInterval(this.update, 1000);
},
update() {
const now = Date.now();
this.remain = Math.max(Math.floor((this.endTime - now) / 1000), 0);
this.timeStr = this.formatTime(this.remain);
if (this.remain <= 0) {
this.clear();
this.$emit('finish');
if (this.onFinish) this.onFinish();
// 鸿蒙平台可结合本地通知API提醒
#ifdef APP-PLUS
uni.showToast({ title: '倒计时结束', icon: 'none' });
#endif
}
},
clear() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
formatTime(sec) {
let h = Math.floor(sec / 3600);
let m = Math.floor((sec % 3600) / 60);
let s = sec % 60;
return [h, m, s].map(v => v < 10 ? '0' + v : v).join(':');
},
},
mounted() {
this.start();
},
beforeDestroy() {
this.clear();
},
};
</script>
3. 样式设计
css
<style scoped>
.countdown {
font-size: 40rpx;
color: #ff4d4f;
text-align: center;
padding: 24rpx 0;
letter-spacing: 2rpx;
}
</style>
三、父页面集成与提醒示例
vue
<template>
<countdown :duration="120" @finish="onFinish" />
</template>
<script>
import Countdown from '@/components/Countdown.vue';
export default {
components: { Countdown },
methods: {
onFinish() {
// 业务提醒逻辑
#ifdef APP-PLUS
uni.showModal({ title: '提醒', content: '倒计时已结束!' });
#endif
},
},
};
</script>
四、鸿蒙平台适配与优化建议
- 生命周期适配 :鸿蒙设备切后台/前台时,建议在
onHide
/onShow
钩子保存与恢复剩余时间,防止倒计时异常。 - 本地通知提醒:鸿蒙支持 JSAPI,可结合原生通知能力在倒计时结束时推送本地提醒。
- 分辨率适配 :全程使用
rpx
单位,保证不同鸿蒙设备下显示一致。 - 性能优化:倒计时刷新频率建议为1秒,避免高频率更新导致卡顿。
- 多场景扩展:可扩展为多组倒计时、循环倒计时等,适配更多业务需求。
五、实际应用案例
- 秒杀活动:商品详情页倒计时,结束后自动刷新状态。
- 任务提醒:待办事项到期提醒,结合本地通知。
- 考试倒计时:考试页面精准计时,结束自动提交。
六、总结与展望
倒计时与提醒功能是移动端常见的交互需求。通过 UniApp 的跨平台能力,我们可以高效实现兼容鸿蒙的倒计时与提醒组件。未来还可结合原生通知、定时任务等能力,进一步丰富提醒场景。希望本文的讲解和代码示例能为你的项目带来启发,欢迎留言交流更多鸿蒙适配经验!