现在,我的组件正在工作,在给定time_start
和time_end
的情况下它将显示持续时间,但是如果没有给出time_end
,我将尝试显示实时持续时间。所有这些逻辑都发生在calculateDuration方法内部,但是我不得不创建另一个包装器方法liveDuration
以保持每秒更新一次calculateDuration。使用下面的代码,我看到错误每秒出现在控制台中
Uncaught SyntaxError: Unexpected identifier
但是,如果我单击控制台中的错误,则会显示正确的持续时间
0 hrs 1 min 7 sec
但是,模板中呈现的所有内容都是一个静态数字(例如5或7),永远不会更新,我不确定这些数字来自何处。
如何更新以下代码,以便在模板中每秒实时更新持续时间?
<template>
<div class="executions">
<h3>Recent Jobs</h3>
<table>
<template>
<tr>
<td><b>Job</b></td>
<td><b>Duration</b></td>
<td><b>Result</b></td>
</tr>
<tr>
<td>{{ item.id }}</td>
<td>
<template v-if="item.duration == 'N/A'">
{{ liveUpdate(item.time_start) }}
</template>
<template v-else>
{{ item.duration }}
</template>
</td>
<td>{{ item.status }}</td>
</tr>
</template>
</table>
</div>
</template>
<script>
import moment from "moment";
export default {
name: "Executions",
data() {
return {
job_execs: []
};
},
methods: {
calculateDuration: function(time_start, time_end) {
let duration = "N/A"
if (time_start && time_end) {
time_start = moment(time_start)
time_end = moment(time_end)
duration = moment.duration(time_end.diff(time_start));
if (duration.seconds() == 0) {
duration = "N/A";
} else {
duration =
duration.hours() +
" hrs " +
duration.minutes() +
" min " +
duration.seconds() +
" sec";
}
time_start = time_start.format("LLL")
time_end = time_end.format("LLL")
}
if (time_start == null) {
time_start = "N/A";
}
else {
time_start = moment(time_start).format("LLL")
}
if (time_end == null) {
time_end = "N/A";
}
else {
time_end = moment(time_end).format("LLL")
}
return {time_start, time_end, duration}
},
liveDuration: function(time_start) {
let now = moment();
let duration = "N/A"
console.log(time_start)
if (time_start) {
console.log(time_start)
time_start = moment(time_start)
console.log(time_start)
let time_current = moment()
console.log(time_current)
duration = moment.duration(time_current.diff(time_start));
console.log(duration)
if (duration.seconds() == 0) {
duration = "N/A";
} else {
duration =
duration.hours() +
" hrs " +
duration.minutes() +
" min " +
duration.seconds() +
" sec";
}
}
return duration
},
liveUpdate: function(time_start) {
let that=this;
let time_live = setInterval(that.liveDuration(time_start), 1000);
return time_live
},
},
created() {
this.jobExecEndpoint = 'http://test'
fetch(this.jobExecEndpoint)
.then(response => response.json())
.then(body => {
for (let i = 0; i < body.length; i++) {
let {time_start, time_end, duration} = this.calculateDuration(body[i].time_start, body[i].time_end);
this.job_execs.push({
id: body[i].id,
time_start: time_start,
time_end: time_end,
duration: duration,
status: body[i].status.name,
});
}
})
.catch(err => {
console.log("Error Fetching:", this.jobExecEndpoint, err);
return { failure: this.jobExecEndpoint, reason: err };
});
}
};
</script>
答案 0 :(得分:0)
我认为主要问题在于liveUpdate方法返回的值。它返回一个setInterval处理程序,而不是您想要显示的持续时间。 第二个问题是,即使该方法返回正确的值,它也不会自动更新。例如,如果要使其每1秒更新一次,则应在挂接的挂钩中使用setInterval并在每个间隔中更新数据。更新数据将自动并以反应方式更新视图。