dt_timer.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <view class="dt-timer">
  3. <view class="hours">{{hours}}</view>
  4. <view class="separator">{{separator}}</view>
  5. <view class="minutes">{{minutes}}</view>
  6. </view>
  7. </template>
  8. <script>
  9. export default {
  10. props:{
  11. start:{
  12. type:String,
  13. default:''
  14. },
  15. separator:{
  16. type:String,
  17. default:':'
  18. }
  19. },
  20. data(){
  21. return {
  22. timer:null,
  23. hours:'00',
  24. minutes:'00'
  25. }
  26. },
  27. watch:{
  28. start(n,o){
  29. if(n){
  30. this.initTimer()
  31. }
  32. }
  33. },
  34. methods:{
  35. timeout(diffMinutes){
  36. if(diffMinutes<=0){
  37. clearTimeout(this.timer)
  38. this.timer = null
  39. // 倒计时结束
  40. this.$emit('timeover')
  41. return
  42. }
  43. let m = diffMinutes % 60
  44. let h = (diffMinutes - m) / 60
  45. this.hours = h<10?('0'+h):h
  46. this.minutes = m<10?('0'+m):m
  47. this.timer = setTimeout(()=>{
  48. diffMinutes = diffMinutes - 1
  49. console.log(51,diffMinutes)
  50. this.timeout(diffMinutes)
  51. },60000)
  52. },
  53. initTimer(){
  54. let startStr = this.start.substr(0,16)
  55. let expire = this.$util.createDate(startStr)
  56. let diffMills = expire.getTime() - (new Date().getTime())
  57. // console.log(58,diffMills)
  58. let diffSeconds = parseInt(diffMills / 1000)
  59. let diffMinutes = parseInt(diffSeconds / 60) + 1
  60. // diffMinutes 加 1 是因为有的接口返回的过期时间不包含秒数,故这里增加1分钟
  61. // 由接口处理"中间1分钟误差", 导致有可能出现的过期发起支付问题
  62. if(diffMills<=0){
  63. console.log('63 stop',diffMinutes,this.start)
  64. this.$emit('timeover')
  65. }else{
  66. console.log('63 start',diffMinutes,this.start)
  67. this.timeout(diffMinutes)
  68. }
  69. },
  70. },
  71. created(){
  72. if(this.start){
  73. this.initTimer()
  74. }
  75. },
  76. beforeDestroy() {
  77. if(this.timer){
  78. clearTimeout(this.timer)
  79. this.timer = null
  80. console.log('clearTimeout')
  81. }
  82. }
  83. }
  84. </script>
  85. <style lang="scss">
  86. .dt-timer{
  87. display:inline-flex;
  88. }
  89. </style>