index.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import util from '../../utils/util'
  2. Component({
  3. properties: {
  4. // useSlot: Boolean,
  5. // 截止的时间
  6. date: String,
  7. // 分隔符, colon为英文冒号,zh为中文
  8. separator: {
  9. type: String,
  10. value: 'zh'
  11. },
  12. // 组件样式, text为纯文本,custom为带背景色
  13. style: {
  14. type: String,
  15. value: 'text'
  16. },
  17. },
  18. data: {
  19. // 倒计时数据
  20. dynamic: {
  21. day: '00',
  22. hou: '00',
  23. min: '00',
  24. sec: '00'
  25. },
  26. // 分隔符文案
  27. separatorText: {
  28. day: '天',
  29. hou: '时',
  30. min: '分',
  31. sec: '秒'
  32. }
  33. },
  34. attached() {
  35. // 分隔符文案
  36. this.separatorText()
  37. // 开始倒计时
  38. this.onTime()
  39. },
  40. detached() {
  41. },
  42. methods: {
  43. // 分隔符文案
  44. separatorText() {
  45. const separatorText = this.data.separatorText
  46. if (this.data.separator === 'colon') {
  47. separatorText.day = ':'
  48. separatorText.hou = ':'
  49. separatorText.min = ':'
  50. separatorText.sec = ''
  51. }
  52. this.setData({
  53. separatorText
  54. })
  55. },
  56. // 开始倒计时
  57. onTime(deep = 0) {
  58. const app = this
  59. const dynamic = {}
  60. // 获取当前时间,同时得到活动结束时间数组
  61. const newTime = new Date().getTime()
  62. // 对结束时间进行处理渲染到页面
  63. const endTime = new Date(util.format_date(app.data.date)).getTime();
  64. // 如果活动未结束,对时间进行处理
  65. if ((endTime - newTime) <= 0) {
  66. return false
  67. }
  68. const diffTime = (endTime - newTime) / 1000;
  69. // 获取时、分、秒
  70. const day = parseInt(diffTime / 86400),
  71. hou = parseInt(diffTime % 86400 / 3600),
  72. min = parseInt(diffTime % 86400 % 3600 / 60),
  73. sec = parseInt(diffTime % 86400 % 3600 % 60);
  74. dynamic.day = app.timeFormat(day)
  75. dynamic.hou = app.timeFormat(hou)
  76. dynamic.min = app.timeFormat(min)
  77. dynamic.sec = app.timeFormat(sec)
  78. // 渲染,然后每隔一秒执行一次倒计时函数
  79. app.setData({
  80. dynamic
  81. })
  82. // 判断倒计时是否结束
  83. const isEnd = app.isEnd()
  84. // 结束后执行回调函数
  85. if (isEnd) {
  86. deep > 0 && app.triggerEvent('finish')
  87. }
  88. // 重复执行
  89. if (!isEnd) {
  90. setTimeout(() => {
  91. app.onTime(++deep)
  92. }, 1000)
  93. }
  94. },
  95. // 判断倒计时是否结束
  96. isEnd() {
  97. const {
  98. dynamic
  99. } = this.data
  100. if (dynamic.day == '00' && dynamic.hou == '00' && dynamic.min == '00' && dynamic.sec == '00') {
  101. return true
  102. }
  103. return false
  104. },
  105. /**
  106. * 小于10的格式化函数
  107. */
  108. timeFormat(value) {
  109. return value < 10 ? '0' + value : value
  110. }
  111. }
  112. })