countDown.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <div class="count-down">
  3. <slot>
  4. {{content}}
  5. </slot>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. content: '',
  13. }
  14. },
  15. props: {
  16. endTime: {
  17. type: Number,
  18. default: 0
  19. },
  20. endText: {
  21. type: String,
  22. default: ''
  23. },
  24. callback: {
  25. type: Function,
  26. default: null
  27. }
  28. },
  29. mounted() {
  30. this.countdowm(this.endTime)
  31. },
  32. methods: {
  33. countdowm(timestamp) {
  34. let self = this;
  35. let timer = setInterval(function () {
  36. let nowTime = new Date();
  37. let endTime = new Date(timestamp * 1000);
  38. let t = endTime.getTime() - nowTime.getTime();
  39. if (t > 0) {
  40. let day = Math.floor(t / 86400000);
  41. let hour = Math.floor((t / 3600000) % 24);
  42. let min = Math.floor((t / 60000) % 60);
  43. let sec = Math.floor((t / 1000) % 60);
  44. hour = hour < 10 ? "0" + hour : hour;
  45. min = min < 10 ? "0" + min : min;
  46. sec = sec < 10 ? "0" + sec : sec;
  47. let format = '';
  48. if (day > 0) {
  49. format = `${day}天${hour}小时${min}分${sec}秒`;
  50. }
  51. if (day <= 0 && hour > 0) {
  52. format = `${hour}小时${min}分${sec}秒`;
  53. }
  54. if (day <= 0 && hour <= 0) {
  55. format = `${min}分${sec}秒`;
  56. }
  57. self.content = self.endText + ' ' + format;
  58. } else {
  59. clearInterval(timer);
  60. self.content = '';
  61. self._callback();
  62. }
  63. }, 1000);
  64. },
  65. _callback() {
  66. if (this.callback && this.callback instanceof Function) {
  67. this.callback(...this);
  68. }
  69. }
  70. }
  71. }
  72. </script>
  73. <style lang="scss" rel="stylesheet/scss" scoped>
  74. .count-down {
  75. margin: 10px;
  76. color: $red;
  77. }
  78. </style>