countdown-tag.vue 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <template>
  2. <view class="countdown-tag" :style="{ backgroundColor: color }">
  3. <text class="countdown-text" :style="{ color: textColor }">{{ remainingText }}</text>
  4. </view>
  5. </template>
  6. <script>
  7. import { parseDate } from '@/utils/format.js'
  8. export default {
  9. name: 'CountdownTag',
  10. props: {
  11. endTime: { type: String, default: null },
  12. color: { type: String, default: '#FF6B00' },
  13. textColor: { type: String, default: '#FFFFFF' }
  14. },
  15. data() {
  16. return { remainingText: '' }
  17. },
  18. created() {
  19. this._timer = null
  20. this._tick()
  21. this._timer = setInterval(() => this._tick(), 1000)
  22. },
  23. beforeDestroy() {
  24. if (this._timer) clearInterval(this._timer)
  25. },
  26. methods: {
  27. _tick() {
  28. if (!this.endTime) {
  29. this.remainingText = ''
  30. return
  31. }
  32. var end = parseDate(this.endTime)
  33. if (!end) {
  34. this.remainingText = ''
  35. return
  36. }
  37. var diff = end.getTime() - Date.now()
  38. if (diff <= 0) {
  39. this.remainingText = '已结束'
  40. return
  41. }
  42. var days = Math.floor(diff / 86400000)
  43. var hours = Math.floor((diff % 86400000) / 3600000)
  44. var mins = Math.floor((diff % 3600000) / 60000)
  45. var secs = Math.floor((diff % 60000) / 1000)
  46. if (days > 0) {
  47. this.remainingText = days + '天' + hours + '时' + mins + '分' + secs + '秒'
  48. } else if (hours > 0) {
  49. this.remainingText = hours + '时' + mins + '分' + secs + '秒'
  50. } else {
  51. this.remainingText = mins + '分' + secs + '秒'
  52. }
  53. if (diff < 3600000) {
  54. this.remainingText = '即将结束'
  55. }
  56. }
  57. }
  58. }
  59. </script>
  60. <style scoped>
  61. .countdown-tag {
  62. display: inline-block;
  63. padding: 4rpx 12rpx;
  64. border-radius: 8rpx;
  65. font-size: 22rpx;
  66. margin-top: 6rpx;
  67. }
  68. .countdown-text {
  69. font-weight: bold;
  70. }
  71. </style>