vue 列表数据倒计时,在页面销毁前需要清除定时器,否着会报错。
export default {
data() {
return {
list: []
}
},
mounted() {
for (let i in this.list) {
this.countDown(i)
}
},
destroyed() {
// 在这个生命周期中清除定时器
for (let i in this.list) {
clearInterval(this.list[i].countDownFn);
}
},
methods: {
formatTime(s) {
let Day = parseInt(s / 60 / 60 / 24, 10)
let Hour = parseInt(s / 60 / 60 % 24, 10)
let Minute = parseInt(s / 60 % 60, 10)
let Second = parseInt(s % 60, 10)
let res = {
d: Day,
h: (Hour + "").padStart(2, "0"),
m: (Minute + "").padStart(2, "0"),
s: (Second + "").padStart(2, "0")
}
return res;
},
countDown(i) {
let item = this.list[i]
this.list[i].countDownFn = setInterval(() => {
item.time_remaining -= 1
if (item.time_remaining <= 0) {
clearInterval(this.list[i].countDownFn);
} else {
item.countDownTime = item.time_remaining > 0 ? this.formatTime(item.time_remaining) : {}
}
}, 1000);
}
}
}