sms-btn.uvue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <template>
  2. <slot :disabled="isDisabled" :countdown="countdown" :btnText="btnText">
  3. <cl-button text :disabled="isDisabled" @tap="open">
  4. {{ btnText }}
  5. </cl-button>
  6. </slot>
  7. </template>
  8. <script lang="ts" setup>
  9. import { computed, reactive, ref } from "vue";
  10. import { useUi } from "@/uni_modules/cool-ui";
  11. import { request, type Response, isDark, t, $t, parse } from "@/.cool";
  12. import { sendSmsCode } from "@/api/user";
  13. const props = defineProps({
  14. phone: String
  15. });
  16. const ui = useUi();
  17. type Captcha = {
  18. visible: boolean;
  19. loading: boolean;
  20. sending: boolean;
  21. img: string;
  22. };
  23. // 验证码
  24. const captcha = reactive<Captcha>({
  25. visible: false,
  26. loading: false,
  27. sending: false,
  28. img: ""
  29. });
  30. // 倒计时
  31. const countdown = ref(0);
  32. // 是否禁用
  33. const isDisabled = computed(() => countdown.value > 0 || props.phone == "");
  34. // 按钮文案
  35. const btnText = computed(() =>
  36. countdown.value > 0 ? $t("{n}s后重新获取", { n: countdown.value }) : t("获取验证码")
  37. );
  38. // 开始倒计时
  39. function startCountdown() {
  40. countdown.value = 60;
  41. let timer: number = 0;
  42. function fn() {
  43. countdown.value--;
  44. if (countdown.value < 1) {
  45. clearInterval(timer);
  46. }
  47. }
  48. // @ts-ignore
  49. timer = setInterval(() => {
  50. fn();
  51. }, 1000);
  52. fn();
  53. }
  54. // 发送短信
  55. async function send() {
  56. captcha.sending = true;
  57. const res = await sendSmsCode({
  58. mobile: props.phone,
  59. randomStr: 12,
  60. messageType: 1
  61. })
  62. ui.showToast({
  63. message: t("短信已发送,请查收")
  64. });
  65. startCountdown();
  66. captcha.sending = false;
  67. }
  68. // 打开
  69. function open() {
  70. if (props.phone != "") {
  71. if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(props.phone!)) {
  72. captcha.visible = true;
  73. send();
  74. } else {
  75. ui.showToast({
  76. message: t("请填写正确的手机号格式")
  77. });
  78. }
  79. }
  80. }
  81. defineExpose({
  82. open,
  83. send,
  84. startCountdown
  85. });
  86. </script>