Timer.vue 950 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <template>
  2. <span>
  3. {{ timer }}
  4. </span>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'Timer',
  9. props: {
  10. time: {
  11. type: Number, // in second
  12. default: 0
  13. }
  14. },
  15. emits: ['stop'],
  16. data () {
  17. return {
  18. step: 'login',
  19. localTime: 0,
  20. interval: null
  21. }
  22. },
  23. computed: {
  24. timer () {
  25. const seconds = (this.localTime % 60).toString().padStart(2, '0')
  26. const minutes = (Math.floor(this.localTime / 60)).toString().padStart(2, '0')
  27. return minutes + ':' + seconds
  28. }
  29. },
  30. mounted() {
  31. this.startTimer()
  32. },
  33. methods: {
  34. startTimer () {
  35. this.localTime = this.time
  36. this.interval = setInterval(() => {
  37. if (this.localTime <= 0) {
  38. this.stopTimer()
  39. } else {
  40. this.localTime--
  41. }
  42. }, 1000)
  43. },
  44. stopTimer () {
  45. this.localTime = 0
  46. clearInterval(this.interval)
  47. this.$emit('stop')
  48. }
  49. }
  50. }
  51. </script>