前端页面列表多个倒计时功能实现

在开发中,我们可能会遇到后端后悔的列表数据中有时间的字段需要在页面上形成每一条数据都有一个倒计时的效果,下面我讲讲我在开发项目中遇到的问题并讲解如何实现页面多个倒计时.

一,效果图

这两个项目我都是用到了列表倒计时的使用,下面告诉大家如何实现

二,列表倒计时的实现

其中,后端返回给我的数据中,每个时间的格式为2023-05-17 09:20:07这种类型的,我们在获取到数据的时候就应该处理一下返回的数据

2.1 获取到数据时 定义倒计时结束时间 结束时间根据你自己的要求设置,我这边是根据返回的item.createTime设置的 并转换成时间戳

async getData() {
      try {
        this.loading = true
        const res = await getVerificationPage(this.queryInfo)
        if (res.code === 0) {
          this.tableData = res.result.data
          this.total = res.result.total

          // 获取到列表数据 对裂变数据进行动态添加新的键值
          this.tableData.forEach((item) => {

            // 这边我们定义一个 倒计时结束的时间 转换成时间戳
            const endTime = Date.parse(item.createTime) + 10 * 60 * 1000

            // vue2动态添加的对象是不具备响应式的 所以用$set

            // 结束时间 - 当前时间 如果小于等于0 那么就不需要再倒计时了
            if (endTime - new Date().getTime() <= 0) {
              this.$set(item, 'countDown', '无效')

            // 结束时间 - 当前时间 > 0的时候 设置倒计时的数据
            } else {
              this.$set(item, 'countDown', '00分00秒')
              this.$set(item, 'endTime', endTime)
            }
          })

          this.$nextTick(() => {
            this.setTableHeight()
          })
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
},

2.2 在methods定义倒计时的方法 并在mounted开启

methods: {
  startCountDown() {
    // 定义一个倒计时setInterval
    this.timer = setInterval(() => {

      // finishedCount 计算页面倒计时有几个结束了
      let finishedCount = 0
        
      // 遍历我们处理好了的表格数据
      for (let key in this.tableData) {

        // 结束时间
        let endTime = parseInt(this.tableData[key]['endTime'])

        // 当前时间
        let nowTime = new Date().getTime()

        // 如果结束时间大于当前时间 开始倒计时; 否则 当前行的倒计时显示无效
        let rightTime = endTime - nowTime
        if (rightTime > 0) {
          let mm = Math.floor((rightTime / 1000 / 60) % 60)
          mm = mm < 10 ? '0' + mm : mm
          let ss = Math.floor((rightTime / 1000) % 60)
          ss = ss < 10 ? '0' + ss : ss
          this.tableData[key]['countDown'] = `${mm}分${ss}秒`
        } else {
          this.tableData[key]['countDown'] = `无效`
          finishedCount++
        }
     }
     if (finishedCount === this.tableData.length) { // 如果所有计时器都完成了,则清除定时器   
          clearInterval(this.timer)
        }
      }, 1000)
  },

  someEventHandler() {
    // 清除旧的定时器
    clearInterval(this.timer)
    // 开启新的倒计时
    this.startCountDown()
  },
},

// 在mounted中调用开启
mounted() {
   // 实现倒计时
   this.someEventHandler()
},

//页面销毁的时候清除定时器
beforeDestroy() {
  // 清除倒计时
  clearTimeout(this.timer)
  this.timer = null
},

这样,我们的列表多个定时器功能就实现了,如果有不懂的小伙伴,欢迎在评论区留言,大家一起交流解决.

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
前端实现多个商品列表倒计时,可以使用 JavaScript 和定时器来实现。以下是一个简单的实现示例: HTML 代码: ```html <div class="countdown"> <div class="countdown-item"> <span class="countdown-value" id="countdown-1"></span> <span class="countdown-label">秒</span> </div> <div class="countdown-item"> <span class="countdown-value" id="countdown-2"></span> <span class="countdown-label">秒</span> </div> <!-- 添加更多商品倒计时 --> </div> ``` CSS 代码: ```css .countdown { display: flex; justify-content: center; } .countdown-item { margin: 0 10px; } .countdown-value { font-size: 24px; font-weight: bold; } .countdown-label { font-size: 16px; margin-left: 5px; } ``` JavaScript 代码: ```js // 假设商品倒计时的时间戳已经存储在一个数组中,每个时间戳对应一个商品 const countdownTimestamps = [1609459200, 1609462800]; // 获取当前时间戳 const currentTimestamp = Math.floor(Date.now() / 1000); // 计算每个商品的倒计时秒数 const countdownSeconds = countdownTimestamps.map(timestamp => timestamp - currentTimestamp); // 获取倒计时元素 const countdownElements = document.querySelectorAll('.countdown-value'); // 更新倒计时元素的显示 function updateCountdown() { countdownSeconds.forEach((seconds, index) => { if (seconds <= 0) { countdownElements[index].textContent = '已结束'; } else { const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; countdownElements[index].textContent = `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`; } }); } // 每秒更新一次倒计时 setInterval(() => { countdownSeconds.forEach((seconds, index) => { if (seconds > 0) { countdownSeconds[index] = seconds - 1; } }); updateCountdown(); }, 1000); // 页面加载时更新一次倒计时 updateCountdown(); ``` 这段代码实现了在页面中显示多个商品的倒计时,每秒钟自动更新一次。可以根据实际需求修改时间戳数组和 HTML 结构以适应不同的场景。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值