vue3 数据可视化大屏获取验证码

vue yekong 334℃

数据可视化大屏项目开发中,登录页需要一个验证码发送功能,这里我们来实现这个功能。

使用

<captcha :phone="phone"></captcha>

创建组件captcha

创建组件captcha

组件接收电话号码,使用label来显示获取验证码,点击发送后,触发接口执行发送,发送成功进行60s倒计时。

<template>
  <label :class="labelClass" @click="requestCaptcha">{{ labelText }}</label>
</template>

<script>
import {getAuthCode} from '@/api/api/LargeScreenData.js'
import {ElMessage} from 'element-plus';  // 引入 Element 的 Message 模块
export default {
  data() {
    return {
      isCaptchaActive: true,   // 判断验证码是否可点击
      countdown: 0            // 倒计时秒数
    }
  },
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  computed: {
    labelText() {
      return this.countdown > 0 ? `${this.countdown}秒后重试` : '获取验证码';
    },
    labelClass() {
      return {
        'active': this.isCaptchaActive,
        'inactive': !this.isCaptchaActive
      };
    }
  },
  methods: {
    async requestCaptcha() {
      if (!this.isCaptchaActive) return;  // 如果不可点击则直接返回

      if (!this.phone) {
        ElMessage.error('请输入电话号码');
        return;
      }

      try {
        // 请求验证码 API
        const response = await getAuthCode({phone: this.phone});
        console.log(response)
        // 检查返回的响应码
        if (response.code === 0) {
          // 登录成功,重定向到主页
          ElMessage({
            message: '发送成功',
            type: 'success',
          })
          // 设置验证码不可点击并启动倒计时
          this.isCaptchaActive = false;
          this.countdown = 60;
          const interval = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(interval);
              this.isCaptchaActive = true;
            }
          }, 1000);
        } else {
          // 登录失败,显示错误消息
          ElMessage.error(response.message);
        }

      } catch (error) {
        console.error('Error fetching captcha:', error);
      }
    }
  }
}
</script>

<style scoped>
label {
  cursor: pointer;
  position: absolute;
  right: 10px;
  width: auto;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.active {
  color: #78a8e5;
}

.inactive {
  color: gray;
}
</style>

喜欢 (0)