code.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { ref } from 'vue'
  2. import { sendSmsCode } from '@/api/common'
  3. import { modalStore } from '@/store/modal'
  4. import dayjs from 'dayjs';
  5. import test from './test'
  6. const modal = modalStore()
  7. // 发送验证码
  8. export const getSmsCode = (event, mobile) => {
  9. const lastSendTimer = modal.lastTimer[event];
  10. if (typeof lastSendTimer === 'undefined') {
  11. uni.showToast({
  12. title: '短信发送事件错误'
  13. })
  14. return;
  15. }
  16. const duration = dayjs().unix() - lastSendTimer;
  17. const canSend = duration >= 60;
  18. if (!canSend) {
  19. uni.showToast({
  20. title: '请稍后再试'
  21. })
  22. return;
  23. }
  24. // 只有 mobile 非空时才校验。因为部分场景(修改密码),不需要输入手机
  25. if (mobile && !test.mobile(mobile)) {
  26. uni.showToast({
  27. title: '手机号码格式不正确'
  28. })
  29. return;
  30. }
  31. // 发送验证码 + 更新上次发送验证码时间
  32. let scene = -1;
  33. switch (event) {
  34. case 'resetPassword':
  35. scene = 4;
  36. break;
  37. case 'changePassword':
  38. scene = 3;
  39. break;
  40. case 'changeMobile':
  41. scene = 2;
  42. break;
  43. case 'smsLogin':
  44. scene = 30; // 对接门墩短信登录
  45. break;
  46. }
  47. sendSmsCode({ phone: mobile, scene }).then((res) => {
  48. if (res.code === 0) {
  49. uni.showToast({
  50. title: '发送成功,请注意查收',
  51. icon: 'success',
  52. duration: 2000
  53. })
  54. modal.$patch((state) => {
  55. state.lastTimer[event] = dayjs().unix();
  56. })
  57. }
  58. })
  59. }
  60. // 验证码倒计时
  61. export const getSmsTimer = (event) => {
  62. const lastSendTimer = modal.lastTimer[event]
  63. if (typeof lastSendTimer === 'undefined') {
  64. uni.showToast({
  65. title: '短信发送事件错误'
  66. })
  67. return
  68. }
  69. const duration = ref(dayjs().unix() - lastSendTimer - 60)
  70. const canSend = duration.value >= 0
  71. if (canSend) {
  72. return '获取验证码'
  73. }
  74. if (!canSend) {
  75. setTimeout(() => {
  76. duration.value++;
  77. }, 1000);
  78. return -duration.value.toString() + ' 秒'
  79. }
  80. }