目前我的刀片文件上显示了经过的时间。但是要看到更新时间,我需要每次刷新。我想显示动态的经过时间。有办法做到吗?
我当前的代码只是将created_date(从控制器定义)传递给脚本。从那里,我将获得小时、分钟和秒。 (可能会在几天后做)。他们我将其返回到我的刀片文件中。
这是我的刀片文件的一部分:
<table class="table table-bordered small">
<thead>
<tr>
<th width="2%">No</th>
<th width="5%">
Created At
</th>
</tr>
</thead>
<tbody>
<tr v-for="(index,row) in records.data" :class="{'NPI_row_color':NPI_Order(row)}">
<td>@{{index+1}}</td>
<td>
@{{ setTimer(row.created_at) }}
</td>
<tr>
</tbody>
</table>
这是 vue js 脚本:
<script type="text/javascript">
$(function () {
var vm = new Vue({
el: '#shopify_marketplace',
data: {
//some of data here
},
methods: {
//some other methods here
onReload: function(){
//few codes here and there
},
setTimer: function(created_at){
const startDate = new Date(created_at);
const now = new Date();
const elapsedSeconds = Math.floor((now - startDate) / 1000);
const day = Math.floor((elapsedSeconds / 3600));
const hours = Math.floor(elapsedSeconds / 3600);
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
const seconds = elapsedSeconds % 60;
return `${hours}h ${minutes}m ${seconds}s`;
},
},
filters: {
autoCaps: function(value){
if(value != null) {
return value.toLocaleUpperCase();
}
},
},
ready: function () {
this.onReload();
},
});
});
</script>
下图是我当前的显示内容。但是是的,每次都需要刷新才能看到它更新。我可以知道如何让时间运行并“滴答作响”吗?我尝试使用 javascript 中的 setInterval 函数,但失败得很惨。
您应该更改键以强制重新渲染,这将触发该功能,如下所示:
<table class="table table-bordered small">
<thead>
<tr>
<th width="2%">No</th>
<th width="5%">
Created At
</th>
</tr>
</thead>
<tbody>
<tr v-for="(index,row) in records.data" :class="{'NPI_row_color':NPI_Order(row)}">
<td>@{{index+1}}</td>
<td :key="currentTime">
@{{ setTimer(row.created_at) }}
</td>
<tr>
</tbody>
</table>
<script type="text/javascript">
$(function () {
var vm = new Vue({
el: '#shopify_marketplace',
data: {
// some of data here
currentTime: 0 // Add this property to track the current time
},
methods: {
// some other methods here
onReload: function(){
// few codes here and there
},
setTimer: function(created_at){
const startDate = new Date(created_at);
const now = new Date(this.currentTime); // Use the reactive currentTime
const elapsedSeconds = Math.floor((now - startDate) / 1000);
const hours = Math.floor(elapsedSeconds / 3600);
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
const seconds = elapsedSeconds % 60;
return `${hours}h ${minutes}m ${seconds}s`;
},
},
mounted() {
this.onReload();
this.startTimer();
},
methods: {
startTimer() {
// Update the currentTime every second
setInterval(() => {
this.currentTime = new Date().getTime();
}, 1000);
},
// other methods here...
}
});
});
</script>