首頁  >  問答  >  主體

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 天前374

全部回覆(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
  • 取消回覆