js实现商品列表秒杀倒计时

1、实现需求

在秒杀会场的商品列表,每一个商品都需要展示当前的秒杀时间倒计时,且每个商品的结束时间不一样。

2、实现思路

获取当前时间和结束时间,计算时间差,再将时间差转换为日时分秒,使用定时器每秒更新。

3、代码

<script>
	export default {
		props: ["item","endTime"],//父组件传递过来的值
		data() {
			return {
				model: {
					d: '00',//天
					h: '00',//小时
					m: '00',//分钟
					s: '00',//秒
				},
				timedown: null
			}
		},
		watch: { //引入的组件,所以直接监听数据的变化开启倒计时
			endTime: {
				handler(newvalue, oldvalue) {
					if (newvalue) {
						this.countDown()
					}
				},
				immediate: true
			}
		},
		onHide() { //离开页面前清除计时器
			clearTimeout(this.timedown)
			this.timedown = null
		},
		beforeDestroy() {//页面销毁清除计时器
			clearTimeout(this.timedown)
			this.timedown = null
		},
		methods: {
			openPop(id){
				this.$emit('openPop',id)
			},
			timeFormat(param) { //处理数据永远是两位数
				return param < 10 ? '0' + param : param;
			},
			countDown() { //倒计时函数
				let that = this
				// 获取当前时间,同时得到活动结束时间数组
				if (that.item.status == 2) { //判断是否已经结束 已经结束
					clearTimeout(that.timedown)
					return false
				}
				let newTime = new Date().getTime();//获取当前时间
				let endTime = that.endTime;//获取结束时间的时间戳
				// 如果活动未结束,对时间进行处理
				if (endTime - newTime > 0) {
					let time = (endTime - newTime) / 1000;
					// 获取天、时、分、秒
					let d1 = parseInt(time / (60 * 60 * 24));
					let h1 = parseInt(time % (60 * 60 * 24) / 3600);
					let m1 = parseInt(time % (60 * 60 * 24) % 3600 / 60);
					let s1 = parseInt(time % (60 * 60 * 24) % 3600 % 60);
					that.model = {
						d: that.timeFormat(d1),
						h: that.timeFormat(h1),
						m: that.timeFormat(m1),
						s: that.timeFormat(s1)
					}
				} else { //活动已结束,全部设置为'00'
					that.model = {
						d: '00',
						h: '00',
						m: '00',
						s: '00'
					}
					clearTimeout(that.timedown) //活动结束 清除倒计时
					that.timedown = null
					return false;
				}
				// 定时器1秒后再执行一次
				this.timedown = setTimeout(this.countDown.bind(this), 1000);
			},

		}
	}
</script>

猜你喜欢

转载自blog.csdn.net/sxy323/article/details/129836211