verifyCode.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import type { FormInstance, FormItemProp } from "element-plus";
  2. import { clone } from "@pureadmin/utils";
  3. import { ref } from "vue";
  4. const isDisabled = ref(false);
  5. const timer = ref(null);
  6. const text = ref("");
  7. export const useVerifyCode = () => {
  8. const start = async (
  9. formEl: FormInstance | undefined,
  10. props: FormItemProp,
  11. time = 60
  12. ) => {
  13. if (!formEl) return;
  14. const initTime = clone(time, true);
  15. await formEl.validateField(props, isValid => {
  16. if (isValid) {
  17. clearInterval(timer.value);
  18. isDisabled.value = true;
  19. text.value = `${time}`;
  20. timer.value = setInterval(() => {
  21. if (time > 0) {
  22. time -= 1;
  23. text.value = `${time}`;
  24. } else {
  25. text.value = "";
  26. isDisabled.value = false;
  27. clearInterval(timer.value);
  28. time = initTime;
  29. }
  30. }, 1000);
  31. }
  32. });
  33. };
  34. const end = () => {
  35. text.value = "";
  36. isDisabled.value = false;
  37. clearInterval(timer.value);
  38. };
  39. return {
  40. isDisabled,
  41. timer,
  42. text,
  43. start,
  44. end
  45. };
  46. };