vue实现弹窗输入验证码

实现思路:前端输入完账号和密码,点击登录按钮的时候,弹出一个输入验证码的窗口,后端把验证码图片通过base64的字符传给前端,前端把字符当成图片展示出来。输入完验证码,点击确认进行登录,把验证码传给后端,后端判断验证码是否准确。

前端获取验证码的接口

/component/GraphCodeDialog /index.vue 封装成组件

复制代码
<template>
    <el-dialog v-model="dialogVisible" title="获取验证码" width="500">
        <div class="row">
            <img :src="codeImg" style="height: 150px;width:380px" @click="getCodeImge()" />
        </div>
        <div class="row">
            <el-input type="text" placeholder="请输入验证码" v-model="captcode" @keyup.enter="handleAffirm" style="width: 300px;"
                maxlength="6">
            </el-input>
            <el-button type="primary" @click="handleAffirm">确认</el-button>
        </div>
    </el-dialog>
</template>
<script lang='ts'>
import { reactive, getCurrentInstance, toRefs, onMounted, nextTick, defineComponent } from 'vue';
export default defineComponent({
    name: '',
    props: {},
    setup(props: any, { emit }: any) {
        onMounted(() => {
            nextTick(() => { });
        });
        const { proxy } = getCurrentInstance() as any;
        const data = reactive({
            dialogVisible: false,
            codeImg: "",
            captcode: "",
        });

        const handleAffirm = () => {
            if (!data.captcode) return proxy.$message.warning("请输入验证码")
            data.dialogVisible = false
            emit("handleAffirm", data.captcode)
            data.captcode = ''
        }

        const getCodeImge = async () => {
            let res = await proxy.apis.loginCaptchacode()
            if (res.code == 200) {
                data.codeImg = res.data
                data.dialogVisible = true
            } else {
                proxy.$message.error(res.message)
            }
        }

        return { ...toRefs(data), handleAffirm, getCodeImge }
    }
})
</script>
<style scoped lang='scss'>
.row {
    text-align: center;
    margin-bottom: 20px;
}
</style>

页面文件

template代码

复制代码
<!-- 获取图片验证码 -->
<GraphCodeDialog ref="codeImgRef" @handleAffirm="getCodeAffirm"></GraphCodeDialog>

script代码

复制代码
<script setup lang="ts" name="loginIndex">
// 引入组件
const GraphCodeDialog = defineAsyncComponent(() => import('/@/component/GraphCodeDialog /index.vue'));


const getCodeAffirm = (captcode: string) => {
	console.log("验证码=",captcode);
}
</script>

效果图

相关推荐
十一.3664 分钟前
37-38 for循环
前端·javascript·html
波诺波4 分钟前
环境管理器
linux·前端·python
San30.15 分钟前
深入理解浏览器渲染流程:从HTML/CSS到像素的奇妙旅程
前端·css·html
IT_陈寒18 分钟前
5个Python 3.12新特性让你的代码效率提升50%,第3个太实用了!
前端·人工智能·后端
周杰伦_Jay18 分钟前
【Python Web开源框架】Django/Flask/FastAPI/Tornado/Pyramid
前端·python·开源
艾小码38 分钟前
为什么你的JavaScript代码总是出bug?这5个隐藏陷阱太坑了!
前端·javascript
辻戋3 小时前
从零实现React Scheduler调度器
前端·react.js·前端框架
徐同保3 小时前
使用yarn@4.6.0装包,项目是react+vite搭建的,项目无法启动,报错:
前端·react.js·前端框架
Qrun4 小时前
Windows11安装nvm管理node多版本
前端·vscode·react.js·ajax·npm·html5
中国lanwp4 小时前
全局 npm config 与多环境配置
前端·npm·node.js