实现场景:订单列表中多个倒计时(vue)
<template> <div class=""> <div v-for="(item,index) in list" :key="index">{{item.countDownTime }}</div> </div> </template> <script> export default { data() { return { list: [{endTime:"2020-11-02 15:06:36"}, {endTime:"2020-11-12 16:06:36"}, {endTime:"2020-11-08 04:06:36"}, {endTime:"2020-11-17 19:06:36"}] } }, created() { //这里应该写在请求接口拿到数据后,这里我使用模拟数据 for (let i in this.list) { this.list[i].countDownTime = ""; this.countDown(i); } }, methods: { //倒计时 countDownFun(time) { // console.log(time) let startTime = new Date(); //当前时间 let end = new Date(time); //结束时间 // console.log(end) let result = parseInt((end - startTime) / 1000); //计算出豪秒 let d = parseInt(result / (24 * 60 * 60)); //用总共的秒数除以1天的秒数 let h = parseInt((result / (60 * 60)) % 24); //精确小时,用去余 let m = parseInt((result / 60) % 60); //剩余分钟就是用1小时等于60分钟进行趣余 let s = parseInt(result % 60); //当倒计时结束时,改变内容 if (result <= 0) { return "倒计时结束"; } if (h < 10) { h = "0" + h; } if (s < 10) { s = "0" + s; } if (h == 0 && m == 0) { return "剩余" + s + "秒"; } else if (h == 0) { return "剩余" + m + "分" + s + "秒"; } else if(d == 0) { return "剩余" + h + "时" + m + "分" + s + "秒"; } else { return "剩余" + d + "天" + h + "时" + m + "分" + s + "秒"; } }, // 定时器 // 页面多个倒计时 归零时清除 countDown(i) { let that = this; let item = that.list[i]; that.list[i].countDownFn = setInterval(() => { // console.log(that.countDownFun(item.endTime)) if (that.countDownFun(item.countDownTime) == "倒计时结束") { clearInterval(that.list[i].countDownFn); //清除定时器 } else { item.countDownTime = that.countDownFun(item.endTime); that.$set( that.list, item.countDownTime, that.countDownFun(item.endTime) ); } }, 1000); } } }; </script> <style scoped lang="less"> </style>
最终效果
找工作,没有面试题?来看这里, 扫码查看1000+ 前端面试题
WX搜索 【MST题库】小程序查看