金诚优选前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
1.7 KiB

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