For context, I have a table showing incoming calls and the wait time for each call. The data array looks like this:
[ { 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, ... } ]
I'm trying to figure out how to assign setTimeout to each object, but I'm completely lost.
So far I've found that it's possible to make a counter via an observer, but this of course only acts as a "global" counter.
watch: { timerCount: { handler (value) { if (value > 0) { setTimeout(() => { this.timerCount++ }, 1000) } }, immediate: true // This ensures the watcher is triggered upon creation } },
Is there a way to use a function to display the counter on each object? I was thinking something like this:
<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>
Additionally, I want to return the waiting time in the format HH:mm:ss
.
One solution is to wrap
{{ showWaitingTime(call.created_at) }}
with<span>
, which iskey
ed ontimerCount
so that<span>
is re-rendered whentimerCount
changes (thereby callingshowWaitingTime
again to calculate the new Time string): p>In the template, use
<span>
to wrap the timestamp string with thekey
bound totimerCount
:waiting time: {{ showWaitingTime(call.created_at) }}
In the observer on
calls
, usesetInterval
to start the periodic timer. Always stop the timer usingclearInterval
before starting a new timer and when uninstalling the component.Your watcher on
timerCount
is effectively implementingsetInterval
. Remove this code because the code in step 2 eliminates it.In
based on the difference between the given time and nowshowWaitingTime()
, calculateHH:mm:ss
:Demo p>