fetchSmsMixins.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { getSmsCode } from "./api";
  2. const wstorage = {
  3. set(key, value, expire = null) {
  4. window.localStorage.setItem(key, JSON.stringify({ value, expire }));
  5. },
  6. get(key, defaultVal = null) {
  7. const lsvalue = JSON.parse(window.localStorage.getItem(key));
  8. return lsvalue && (!lsvalue.expire || lsvalue.expire > new Date().getTime())
  9. ? lsvalue.value
  10. : defaultVal;
  11. },
  12. remove(key) {
  13. window.localStorage.removeItem(key);
  14. }
  15. };
  16. const codeWaitingTime = 60;
  17. export default {
  18. data() {
  19. return {
  20. isFetchingCode: false,
  21. codeContent: "获取验证码",
  22. codeWaitingTime,
  23. time: codeWaitingTime
  24. };
  25. },
  26. methods: {
  27. setWaitingTime() {
  28. let codetime = wstorage.get(this.nameWaitTime);
  29. if (codetime) {
  30. let num = Math.floor((codetime.expire - new Date().getTime()) / 1000);
  31. if (num > 0) {
  32. this.time = num;
  33. this.isFetchingCode = true;
  34. this.changeContent();
  35. }
  36. }
  37. },
  38. fetchSmsCode() {
  39. this.$refs.modalFormComp.validateField("phone", async valid => {
  40. if (valid) return;
  41. this.isFetchingCode = true;
  42. const data = await getSmsCode(this.modalForm.phone).catch(() => {
  43. this.isFetchingCode = false;
  44. });
  45. if (!data) return;
  46. this.changeContent();
  47. });
  48. },
  49. changeContent() {
  50. if (!this.isFetchingCode) return;
  51. this.codeContent = "倒计时" + this.time + "s";
  52. const circleTime = time => {
  53. let t = setInterval(() => {
  54. if (time > 1) {
  55. time--;
  56. let expire = new Date().getTime() + time * 1000;
  57. wstorage.set(
  58. this.nameWaitTime,
  59. {
  60. time,
  61. expire
  62. },
  63. expire
  64. );
  65. this.codeContent = "倒计时" + time + "s";
  66. } else {
  67. this.time = this.codeWaitingTime;
  68. wstorage.remove(this.nameWaitTime);
  69. this.codeContent = "获取验证码";
  70. this.isFetchingCode = false;
  71. clearInterval(t);
  72. }
  73. }, 1e3);
  74. };
  75. circleTime(this.time);
  76. }
  77. }
  78. };