index.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. Component({
  2. properties: {
  3. target: Number,
  4. showDay: Boolean,
  5. callback: String,
  6. format: Array,
  7. clearTimer: Boolean,
  8. DIY: Boolean
  9. },
  10. externalClasses: ['countdown-class', 'number-calss'],
  11. data: {
  12. time: '',
  13. resultFormat: [],
  14. changeFormat: false
  15. },
  16. ready() {
  17. this.getFormat();
  18. },
  19. methods: {
  20. getFormat() {
  21. const data = this.data;
  22. const len = data.format.length;
  23. if (!data.showDay) data.resultFormat.push('');
  24. if (len >= 3) {
  25. for (let i = 0; i < len; i++) {
  26. if (data.resultFormat.length >= 4) break;
  27. if (data.format[i]) {
  28. data.resultFormat.push(data.format[i].toString());
  29. }
  30. }
  31. if (data.resultFormat.length >= 4) data.changeFormat = true;
  32. }
  33. this.getLastTime();
  34. },
  35. init() {
  36. const self = this;
  37. setTimeout(function () {
  38. self.getLastTime.call(self);
  39. }, 1000);
  40. },
  41. getLastTime() {
  42. const data = this.data;
  43. const gapTime = Math.ceil((data.target - new Date().getTime()) / 1000);
  44. let result = '';
  45. let _result = {};
  46. let time = '00:00:00';
  47. let day = '00';
  48. const format = data.resultFormat;
  49. if (gapTime > 0) {
  50. day = this.formatNum(parseInt(gapTime / 86400));
  51. let lastTime = gapTime % 86400;
  52. const hour = this.formatNum(parseInt(lastTime / 3600));
  53. lastTime = lastTime % 3600;
  54. const minute = this.formatNum(parseInt(lastTime / 60));
  55. const second = this.formatNum(lastTime % 60);
  56. if (data.changeFormat) time = `${hour}${format[1]}${minute}${format[2]}${second}${format[3]}`;
  57. else time = `${hour}:${minute}:${second}`;
  58. _result.hour = hour;
  59. _result.minute = minute;
  60. _result.second = second;
  61. if (!data.clearTimer) this.init.call(this);
  62. } else {
  63. this.endfn();
  64. }
  65. if (data.showDay) {
  66. if (data.changeFormat) {
  67. result = `${day}${format[0]}${time}`;
  68. } else {
  69. result = `${day}d ${time}`;
  70. }
  71. _result.day = day;
  72. } else {
  73. result = time;
  74. }
  75. this.setData({
  76. time: result,
  77. _result,
  78. format
  79. });
  80. },
  81. formatNum(num) {
  82. return num > 9 ? num : `0${num}`;
  83. },
  84. endfn() {
  85. this.triggerEvent('callback', {});
  86. }
  87. }
  88. });