code.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. case 'smsRegister':
  46. scene = 30; // 对接门墩短信登录
  47. break;
  48. }
  49. sendSmsCode({ phone: mobile, scene }).then((res) => {
  50. if (res.code === 0) {
  51. uni.showToast({
  52. title: '发送成功,请注意查收',
  53. icon: 'none',
  54. duration: 2000
  55. })
  56. modal.$patch((state) => {
  57. state.lastTimer[event] = dayjs().unix();
  58. })
  59. }
  60. })
  61. }
  62. // 验证码倒计时
  63. export const getSmsTimer = (event) => {
  64. const lastSendTimer = modal.lastTimer[event]
  65. if (typeof lastSendTimer === 'undefined') {
  66. uni.showToast({
  67. title: '短信发送事件错误'
  68. })
  69. return
  70. }
  71. const duration = ref(dayjs().unix() - lastSendTimer - 60)
  72. const canSend = duration.value >= 0
  73. if (canSend) {
  74. return '获取验证码'
  75. }
  76. if (!canSend) {
  77. setTimeout(() => {
  78. duration.value++;
  79. }, 1000);
  80. return -duration.value.toString() + ' 秒'
  81. }
  82. }