uniapp+vue3封装倒计时

<template>
	<view class="timer flex1">
		<view>Remaining</view>
		<view class="time flex1">{{formatNumber(days)}}</view>
		<view>Day</view>
		<view class="time flex1">{{formatNumber(hours)}}</view>
		<view>:</view>
		<view class="time flex1">{{formatNumber(minutes)}}</view>
		<view>:</view>
		<view class="time flex1">{{ formatNumber(seconds) }}</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		defineProps
	} from 'vue'

	const props = defineProps(['endTime']);
	// 计算剩余秒数,起始时间为现在时间,结束时间为传入的 endTime
	const count = ref(Math.floor((props.endTime - Math.floor(Date.now() / 1000)))); // 剩余秒数

	const days = ref(Math.floor(count.value / (3600 * 24)))
	const hours = ref(Math.floor((count.value % (3600 * 24)) / 3600))
	const minutes = ref(Math.floor((count.value % 3600) / 60))
	const seconds = ref(count.value % 60)

	// 格式化数字,确保始终显示两位数
	const formatNumber = (num) => {
		return num < 10 ? `0${num}` : num
	}
	let timer;
	const startCountDown = () => {
		const update = () => {
			count.value--
			if (count.value <= 0) {
				clearInterval(timer)
			} else {
				updateCountDown()
				setTimeout(update, 1000)
			}
		}
		const timer = setTimeout(update, 1000)
	}

	// 更新倒计时显示
	const updateCountDown = () => {
		days.value = Math.floor(count.value / (3600 * 24))
		hours.value = Math.floor((count.value % (3600 * 24)) / 3600)
		minutes.value = Math.floor((count.value % 3600) / 60)
		seconds.value = count.value % 60
	}
	// 组件挂载时开始倒计时
	onMounted(() => {
		startCountDown()
	})
	// 组件销毁时清除定时器
	onUnmounted(() => {
		clearTimeout(timer)
	})
</script>
<style lang="scss">
	.timer {
		color: #71FA94;
		text-align: center;
		font-size: 12px;

		.time {
			color: #FFFFFF;
			background-image: url("~@/static/images/ramadan/count_down_bg.png"); // 使用CSS变量作为背景图片
			background-repeat: no-repeat;
			background-size: cover;
			height: 26px;
			width: 35px;
			margin: 0px 5px;
		}
	}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值