先说一下场景,一个列表页面(数据批量加载),每个列表的item都有一个倒计时组件,而且每个item的倒计时时间不一样,当某个item倒计时结束后,紧接着进入下一轮倒计时,此时的倒计时由另一个ajax请求获取倒计时时间(只请求当前item的时间)
<timer :code="hi.code" :remain="hi.leftTime" :id="'timer' + hi.code"></timer>
一轮倒计时结束后通过给 attr 给元素绑定一个date-time,利用此date-time重新计算倒计时
这种方法是可以执行到computed的get方法,而且一开始是会更新UI,就是途中 0 0 0 0 0 1之前,但是之后就不会更新UI,
以下是timer.js
///////////////////////////////////////////////////////////////////////////////////////////
Vue.component('timer', {
template: '<div class="timer_wrap" data-name="time" v-html="countDown"></div>',
data(){
return{ count: '', prop: ''}
},
props: ['remain', 'code'],
created() {
this.count = this.remain;
this.prop = 'data-time';
},
computed: {
countDown: {
get: function(){
let self = this;
let time = self.count;
let $timer = $('#timer' + this.code);
let content = '<ol class="s"><span class="sp1">{1}</span><span class="sp2">{2}</span></ol>\
<ol class="f"><span class="sp1">{3}</span><span class="sp2">{4}</span></ol>\
<ol class="m"><span class="sp1">{5}</span><span class="sp2">{6}</span></ol>';
if(time <= 0) {
self.count = $timer.attr(self.prop);
self.refreshDate(self.code);
return self.fmt(content, 0, 0, 0, 0, 0, 0)
} else {
$timer.attr(self.prop, time);
}
let hour = Math.floor(time / 60 / 60);
let hour1 = Math.floor(hour / 10);
let hour2 = Math.floor(hour % 10);
let mn = time - hour * 60 * 60;
let minute = Math.floor(mn / 60);
let minute1 = Math.floor(minute / 10);
let minute2 = Math.floor(minute % 10);
let second = mn - minute * 60;
let second1 = Math.floor(second / 10);
let second2 = Math.floor(second % 10);
console.log(hour1, hour2, minute1, minute2, second1, second2);
return this.fmt(content, hour1, hour2, minute1, minute2, second1, second2)
},
set: function() {
}
}
},
mounted() {
this.start()
},
methods: {
fmt(c) {
for (let i = 1; i < arguments.length; i++) {
c = c.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
}
return c;
},
start() {
let self = this;
let ct = setInterval(function() {
self.count--;
if(self.count <= 0) {
// clearInterval(ct);
}
}, 1000);
},
refreshDate(code) {
let self = this;
Box.ajax({code: code}, Route.Hall.GET_DATA, function (data) {
new Vue({
el: '#timer' + code,
data: eval('(' + data + ')'),
mounted() {
$('#expect' + code).html(this.expect);
$('#timer' + code).attr(self.prop, this.leftTime);
self.count = this.leftTime;
}
})
})
}
}
});
有没人帮帮忙