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

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

一,效果图

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

二,列表倒计时的实现

其中,后端返回给我的数据中,每个时间的格式为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
},

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值