countdown-timer.vue 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <view><slot :time="time" :remain="timeData.remain" :day="timeData.day" :hour="timeData.hour" :minute="timeData.minute" :second="timeData.second" /></view>
  3. </template>
  4. <script>
  5. export default {
  6. props: {
  7. // 倒计时时长(单位:毫秒)
  8. time: {
  9. type: Number,
  10. default: 0
  11. },
  12. // 是否自动
  13. 'autoStart': {
  14. type: Boolean,
  15. default: false
  16. }
  17. },
  18. data() {
  19. return {
  20. timer: null,
  21. timeData: {
  22. remain: 0,
  23. day: 0,
  24. hour: 0,
  25. minute: 0,
  26. second: 0
  27. }
  28. };
  29. },
  30. watch: {
  31. time() {
  32. this.reset()
  33. }
  34. },
  35. methods: {
  36. // 设置timeData
  37. updateTimeData() {
  38. let t = this.timeData.remain;
  39. this.timeData.day = Math.floor(t / 1000 / 60 / 60 / 24);
  40. this.timeData.hour = Math.floor((t / 1000 / 60 / 60) % 24);
  41. this.timeData.minute = Math.floor((t / 1000 / 60) % 60);
  42. this.timeData.second = Math.floor((t / 1000) % 60);
  43. },
  44. // 开启倒计时
  45. startTimer() {
  46. if (this.timer) {
  47. clearInterval(this.timer);
  48. }
  49. if(this.timeData.remain < 1000) {
  50. return
  51. }
  52. this.timer = setInterval(() => {
  53. this.timeData.remain -= 1000;
  54. this.updateTimeData()
  55. if (this.timeData.remain < 1000) {
  56. this.pause()
  57. this.$emit('finish');
  58. }
  59. }, 1000);
  60. },
  61. // 重置倒计时
  62. reset() {
  63. this.timeData.remain = this.time;
  64. this.updateTimeData();
  65. if(this.autoStart) {
  66. this.start()
  67. }
  68. },
  69. // 暂停倒计时
  70. pause() {
  71. if(this.timer) {
  72. clearInterval(this.timer);
  73. this.timer = null
  74. }
  75. },
  76. // 开始倒计时
  77. start() {
  78. if(this.timer) {
  79. return
  80. }
  81. this.startTimer();
  82. }
  83. },
  84. mounted() {
  85. this.reset();
  86. },
  87. beforeDestroy() {
  88. this.pause()
  89. }
  90. };
  91. </script>