这里用到了vue中的Vue.set(),实现数据动态响应。具体用法可以参考Vue.set()实现数据动态响应
<body>
<div id="app" v-cloak>
<div v-for="item in orders">{{item.time}}</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
var page = new Vue({
el: "#app",
data: {
//这里的数据直接换成你接口获取的
orders: [{"times":"2019-07-26 23:00:00"},{"times":"2019-07-27 12:22:14"},{"times":"2019-07-27 10:00:56"}]
},
created: function() {
var self = this;
//这里是在你接口调取成功后 调用time方法
for(var i = 0; i< self.orders.length; i++){
self.time(i);
}
},
methods: {
time: function(i) {
var self = this;
var nowDate = new Date();
var seconds = parseInt((new Date(self.orders[i].times) - nowDate) / 1000);
if (seconds <= 0) {
Vue.set(self.orders[i], "time", "00:00:00"); //当时间差小于0
return;
}
var hours = Math.floor(seconds / (60 * 60));
if (hours < 10) hours = "0" + hours;
seconds = seconds % (60 * 60);
var mins = Math.floor(seconds / 60);
if (mins < 10) mins = "0" + mins;
seconds = seconds % 60;
if (seconds < 10) seconds = "0" + seconds;
Vue.set(self.orders[i], "time", hours + ":" + mins + ":" + seconds);
//每一秒调用一次
setInterval(function() {
self.time(i);
}, 1000);
}
}
})
</script>
</body>