数组Vue js中每个对象的等待时间计数器

Waiting time counter for each object in array Vue js

为了了解上下文,我有一个 table 显示来电和每个呼叫的等待时间。数据数组如下所示:

[
   {
      id: 1,
      patient_name: lorem ipsum,
      created_at: 2022-02-02 09:10:35,
      ...
   },
   {
      id: 2,
      patient_name: dolor ipsum,
      created_at: 2022-02-02 09:00:35,
      ...
   }
]

我想弄清楚如何为每个对象分配一个 setTimeout,但我完全迷路了。

目前为止,我发现可以通过watcher做一个计数器,当然这只是一个“全局”计数器。

watch: {
        timerCount: {
            handler (value) {
                if (value > 0) {
                    setTimeout(() => {
                        this.timerCount++
                    }, 1000)
                }
            },
            immediate: true // This ensures the watcher is triggered upon creation
        }
    },

有没有办法使用函数在每个对象上显示一个计数器?我在想这样的事情:

<template>
    <span v-for="call in calls" :key="call.id">
       Requested at: {{ call.created_at }}
       waiting time: {{ showWaitingTime(call.created_at) }} // <- Not sure if this can be done
    </span>
</template>
...
<script>
    ....
    methods: {
        showWaitingTime (created_at) {
            // get diff in seconds between created_at and now
            // do something here with a timeOut() to increment the object property...
        }
    }
</script>

此外,我想return等待时间HH:mm:ss格式。

一个解决方案是用 <span> 包裹 {{ showWaitingTime(call.created_at) }},即 timerCount 上的 keyed,这样 <span> 就是 re-rendered 当 timerCount 改变时(因此再次调用 showWaitingTime 来计算新的时间字符串):

  1. 在模板中,将时间戳字符串用 <span> 包装起来,其 key 绑定到 timerCount:

    waiting time: <span :key="timerCount">{{ showWaitingTime(call.created_at) }}</span>
    
  2. calls 上的观察器中,使用 setInterval 启动周期性计时器。在启动新计时器之前和卸载组件时,请务必使用 clearInterval 停止计时器。

    export default {
      beforeUnmount() {
        clearInterval(this._updateTimer)
      },
      // Vue 2 equivalent of beforeUnmount()
      beforeDestroy() {
        clearInterval(this._updateTimer)
      },
      watch: {
        calls: {
          handler(calls) {
            clearInterval(this._updateTimer)
            if (calls.length) {
              this._updateTimer = setInterval(() => this.timerCount++, 1000)
            }
          },
          immediate: true,
        },
      },
    }
    
  3. 您在 timerCount 上的观察者正在有效实施 setInterval。删除该代码,因为它已被步骤 2 中的代码省略。

    export default {
      watch: {
        // timerCount: {⋯}  // ⛔️ remove this watch
      }
    }
    
  4. showWaitingTime()中,根据给定时间和现在的差计算HH:mm:ss

    export default {
      methods: {
        showWaitingTime(created_at) {
          const diff = new Date() - new Date(created_at)
          const twoD = x => `${Math.floor(x)}`.padStart(2, '0')
          const HH = twoD((diff / (60 * 60 * 1000)) % 24)
          const mm = twoD((diff / (60 * 1000)) % 60)
          const ss = twoD((diff / 1000) % 60)
          return `${HH}:${mm}:${ss}`
        },
      },
    }
    

demo