为了了解上下文,我有一个表格显示来电和每个呼叫的等待时间。数据数组如下所示:
[
{
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 格式返回等待时间。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
一种解决方案是用
<span>包装{{ showWaitingTime(call.created_at) }},即keyed 在timerCount上,以便当timerCount更改时重新渲染<span>(从而再次调用showWaitingTime来计算新的时间字符串) : p>在模板中,使用
<span>包装时间戳字符串,该key绑定到timerCount:waiting time: {{ showWaitingTime(call.created_at) }}在
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, }, }, }您在
timerCount上的观察程序正在有效地实现setInterval。删除该代码,因为步骤 2 中的代码已消除了该代码。export default { watch: { // timerCount: {⋯} // ⛔️ remove this watch } }在
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}` }, }, }演示 p>