index.js 2.6 KB

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