verifyCode.ts 1.1 KB

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