code.js 2.1 KB

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