sms.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { ref } from 'vue';
  2. import { lls } from '@/utils/storage';
  3. export default function useSms(name = 'sms') {
  4. const defaultCodeWaitingTime = 60;
  5. const codeWaitingTime = ref(60);
  6. const isFetchingCode = ref(false);
  7. const codeContent = ref('获取验证码');
  8. const nameWaitTime = ref('');
  9. let tSetT: NodeJS.Timer | null = null;
  10. function setWaitingTime(wt: string) {
  11. nameWaitTime.value = wt;
  12. const codetime = lls.get(wt);
  13. if (codetime) {
  14. const num = Math.floor((codetime.expire - new Date().getTime()) / 1000);
  15. if (num > 0) {
  16. codeWaitingTime.value = num;
  17. isFetchingCode.value = true;
  18. changeContent();
  19. }
  20. }
  21. }
  22. setWaitingTime(name);
  23. function changeContent() {
  24. if (!isFetchingCode.value) return;
  25. codeContent.value = `倒计时${codeWaitingTime.value}s`;
  26. const circleTime = (time: number) => {
  27. tSetT = setInterval(() => {
  28. if (time > 1) {
  29. time--;
  30. const expire = new Date().getTime() + time * 1000;
  31. lls.set(
  32. nameWaitTime.value,
  33. {
  34. time,
  35. expire,
  36. },
  37. expire
  38. );
  39. codeContent.value = `倒计时${time}s`;
  40. } else {
  41. clearSetContent();
  42. }
  43. }, 1e3);
  44. };
  45. circleTime(codeWaitingTime.value);
  46. }
  47. function clearSetContent() {
  48. codeWaitingTime.value = defaultCodeWaitingTime;
  49. lls.remove(nameWaitTime.value);
  50. codeContent.value = '获取验证码';
  51. isFetchingCode.value = false;
  52. if (tSetT) clearInterval(tSetT);
  53. }
  54. return {
  55. isFetchingCode,
  56. codeContent,
  57. changeContent,
  58. };
  59. }