123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import { getSmsCode } from "./api";
- const wstorage = {
- set(key, value, expire = null) {
- window.localStorage.setItem(key, JSON.stringify({ value, expire }));
- },
- get(key, defaultVal = null) {
- const lsvalue = JSON.parse(window.localStorage.getItem(key));
- return lsvalue && (!lsvalue.expire || lsvalue.expire > new Date().getTime())
- ? lsvalue.value
- : defaultVal;
- },
- remove(key) {
- window.localStorage.removeItem(key);
- }
- };
- const codeWaitingTime = 60;
- export default {
- data() {
- return {
- isFetchingCode: false,
- codeContent: "获取验证码",
- codeWaitingTime,
- time: codeWaitingTime
- };
- },
- methods: {
- setWaitingTime() {
- let codetime = wstorage.get(this.nameWaitTime);
- if (codetime) {
- let num = Math.floor((codetime.expire - new Date().getTime()) / 1000);
- if (num > 0) {
- this.time = num;
- this.isFetchingCode = true;
- this.changeContent();
- }
- }
- },
- fetchSmsCode() {
- this.$refs.modalFormComp.validateField("phone", async valid => {
- if (valid) return;
- this.isFetchingCode = true;
- const data = await getSmsCode(this.modalForm.phone).catch(() => {
- this.isFetchingCode = false;
- });
- if (!data) return;
- this.changeContent();
- });
- },
- changeContent() {
- if (!this.isFetchingCode) return;
- this.codeContent = "倒计时" + this.time + "s";
- const circleTime = time => {
- let t = setInterval(() => {
- if (time > 1) {
- time--;
- let expire = new Date().getTime() + time * 1000;
- wstorage.set(
- this.nameWaitTime,
- {
- time,
- expire
- },
- expire
- );
- this.codeContent = "倒计时" + time + "s";
- } else {
- this.time = this.codeWaitingTime;
- wstorage.remove(this.nameWaitTime);
- this.codeContent = "获取验证码";
- this.isFetchingCode = false;
- clearInterval(t);
- }
- }, 1e3);
- };
- circleTime(this.time);
- }
- }
- };
|