1 <template> 2 <div class="dat-time"> 3 <div class="time-late"> 4 <span id="time_h1">{{time_h1}}</span> 5 <span id="time_h2">{{time_h2}}</span> 6 <span class="time-kong"></span> 7 <span id="time_m1">{{time_m1}}</span> 8 <span id="time_m2">{{time_m2}}</span> 9 <span class="time-kong"></span> 10 <span id="time_s1">{{time_s1}}</span> 11 <span id="time_s2">{{time_s2}}</span> 12 </div> 13 </div> 14 </template> 15 <script> 16 export default { 17 name: "TimeDown", 18 data() { 19 return { 20 content: "", 21 time_s1: 0, 22 time_s2: 0, 23 time_m1: 0, 24 time_m2: 0, 25 time_h1: 0, 26 time_h2: 0, 27 timer:'' 28 }; 29 }, 30 props: { 31 endTime: { 32 //父组件传入的时间 33 type: Number, 34 default: "" 35 }, 36 callback: { 37 //倒计时结束的回调函数 38 type: Function, 39 default: "" 40 } 41 }, 42 mounted() { 43 this.countdowm(this.endTime); //调用计时器 44 }, 45 destroyed() { 46 clearInterval(_self.timer)//组件销毁时销毁计时器 47 }, 48 methods: { 49 countdowm(endTime) { 50 let _self = this; 51 _self.timer = setInterval(() => { 52 if (endTime > 0) {//判断倒计时剩余的时间 53 endTime--; 54 _self.formateSeconds(endTime);//将秒数转化为特定格式 55 } else {//当倒计时时间小于0清除计时器 56 clearInterval(_self.timer); 57 _self._callback();//倒计时结束调用回调函数 58 } 59 }, 1000); 60 }, 61 //将秒转化为时分秒 62 formateSeconds(endTime) { 63 let _self = this; 64 let secondTime = parseInt(endTime); 65 let minTime = 0; 66 let hTime = 0; 67 if (secondTime > 60) { 68 minTime = parseInt(secondTime / 60); 69 secondTime = parseInt(secondTime % 60); 70 if (minTime > 60) { 71 hTime = parseInt(minTime / 60); 72 minTime = parseInt(minTime % 60); 73 } 74 } 75 _self.time_s1 = _self.x(secondTime, 0, 1); 76 _self.time_s2 = _self.x(secondTime, 1, 2); 77 _self.time_m1 = _self.x(minTime, 0, 1); 78 _self.time_m2 = _self.x(minTime, 1, 2); 79 _self.time_h1 = _self.x(hTime, 0, 1); 80 _self.time_h2 = _self.x(hTime, 1, 2); 81 }, 82 x(num, s1, s2) { 83 return num 84 .toString() 85 .padStart(2, 0) 86 .substring(s1, s2); 87 }, 88 _callback() { 89 let _self = this; 90 if (this.callback && this.callback instanceof Function) { 91 _self.callback.call(_self);//调用回调函数 92 } 93 } 94 }, 95 //倒计时结束之后通过回调函数重新获取倒计时时间 96 //通过watch监控 97 watch: { 98 endTime: { 99 handler(nv, ov) { 100 if (!!nv) {//当获取新的倒计时时间,启动倒计时 101 this.countdowm(this.endTime); 102 } 103 } 104 } 105 } 106 }; 107 </script> 108 <style scoped> 109 </style>
一个倒计时的小组件,有用请支持,有错请指出