1. 程式人生 > >vue 單個倒計時元件

vue 單個倒計時元件

  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>

一個倒計時的小元件,有用請支援,有錯請指出