uni-app vue3 实现72小时倒计时功能

功能介绍 ,数组项有一个下单时间 ,比如今天下单在72小时内可以继续支付,超过则默认取消订单

  1. 页面按钮处 加上倒计时
html 复制代码
<!-- 倒计时 -->
<text v-if="item.timeLeft > 0">{{ formatTime(item.remaining) }}</text>
  1. 逻辑处理
javascript 复制代码
// 第一步 处理接口返回的数据 原本是没有倒计时 remaining这个值的 我们根据状态给数组项加上
console.log("列表数据", res);
res.forEach((item) => {
	if (item.actions.pay) {
		const createTime = new Date(item.create_time).getTime(); // 下单时间处理
		item.endTime = createTime + 72 * 3600 * 1000; // 计算72小时截止时间
		item.remaining = 0; // 剩余时间(毫秒)
		item.timeLeft = true; // 倒计时状态
	}
})
updateAllTimers();

// 第二步 统一定时器
let timer;

// 第三步 更新所有倒计时
const updateAllTimers = () => {
	const now = Date.now();
	listData.value.forEach(item => {
		const diff = item.endTime - now;
		item.remaining = diff;
		item.timeLeft = diff > 0;
	});
};

// 第四步 时间格式化函数
const formatTime = (milliseconds) => {
	if (milliseconds <= 0) return '00:00:00';
	const totalSeconds = Math.floor(milliseconds / 1000);
	const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
	const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
	const seconds = (totalSeconds % 60).toString().padStart(2, '0');
	return `${hours}:${minutes}:${seconds}`;
};

// 生命周期管理
onMounted(() => {
	timer = setInterval(updateAllTimers, 1000);
});

// 卸载
onUnmounted(() => {
	clearInterval(timer);
});
相关推荐
DarkLONGLOVE1 天前
快速上手 Pinia!Vue3 极简状态管理使用教程
javascript·vue.js
宸翰1 天前
解决 uni-app App 端 vue-i18n 占位符丢失:封装跨端可用的 tf 格式化方法
前端·vue.js·uni-app
用户2136610035721 天前
VueRouter进阶-动态路由与嵌套路由
前端·vue.js
暴走的小呆2 天前
Vue 2 中 Object 的变化侦测:从 getter/setter 到 Dep、Watcher、Observer
vue.js
英勇无比的消炎药2 天前
TinyVue v-auto-tip: 文本超长自动提示的优雅方案
vue.js
时光足迹2 天前
uni-app 视频通话实战:康复师与患者视频问诊的 6 个致命 Bug 与解决方案
android·ios·uni-app
时光足迹2 天前
腾讯云 TRTC UniApp SDK 从入门到上线
前端·vue.js·uni-app
时光足迹2 天前
uni-app 里把加密视频嵌入页面播放?我分析了 4 种方案,只有 1 种接近完美
前端·vue.js·uni-app
时光足迹2 天前
JPush UniApp UTS 插件完全参考手册:API、事件与厂商通道一网打尽
vue.js·ios·uni-app
时光足迹2 天前
极光推送全攻略(下):uni-app 代码实现与 iOS 排查实战
vue.js·ios·uni-app