首页  >  问答  >  正文

Vue.js 数组:跟踪每个对象的等待时间

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

[
   {
      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,但我完全迷失了。

到目前为止,我发现可以通过观察者来制作计数器,但这当然只能充当“全局”计数器。

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>

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

P粉970736384P粉970736384205 天前375

全部回复(1)我来回复

  • P粉596161915

    P粉5961619152024-03-28 00:05:39

    一种解决方案是用 <span> 包装 {{ showWaitingTime(call.created_at) }} ,即 keyedtimerCount 上,以便当 timerCount 更改时重新渲染 <span> (从而再次调用 showWaitingTime 来计算新的时间字符串) :

    1. 在模板中,使用 <span> 包装时间戳字符串,该 key 绑定到 timerCount

      waiting time: {{ showWaitingTime(call.created_at) }}
      
    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}`
          },
        },
      }
      

    演示

    回复
    0
  • 取消回复