useSendCode.js 706 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // composables/useSendCode.js
  2. import { ref, onUnmounted } from 'vue'
  3. export function useSendCode() {
  4. const disabled = ref(false)
  5. const text = ref('获取验证码')
  6. let timer = null
  7. let count = 60
  8. const sendCode = () => {
  9. if (disabled.value) return
  10. disabled.value = true
  11. count = 60
  12. text.value = `剩余 ${count}s`
  13. timer = setInterval(() => {
  14. count--
  15. if (count < 0) {
  16. clearInterval(timer)
  17. disabled.value = false
  18. text.value = '重新获取'
  19. return
  20. }
  21. text.value = `剩余 ${count}s`
  22. }, 1000)
  23. }
  24. onUnmounted(() => {
  25. if (timer) clearInterval(timer)
  26. })
  27. return {
  28. disabled,
  29. text,
  30. sendCode
  31. }
  32. }