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>

效果图

相关推荐
Magnum Lehar7 分钟前
wpf3d游戏引擎前端ControlTemplate实现
前端·游戏引擎·wpf
程序员小张丶15 分钟前
基于React Native的HarmonyOS 5.0房产与装修应用开发
javascript·react native·react.js·房产·harmonyos5.0
早该学学了43 分钟前
el-tabs问题解决大总结
前端
中微子44 分钟前
回调函数详解:C++开发者视角下的JavaScript异步艺术
javascript
Sun_light1 小时前
LeetCode 59.「螺旋矩阵」
javascript·算法·面试
星河丶1 小时前
useEffect的清理函数的执行时机
前端·react.js
CAD老兵1 小时前
从 npm 到 Yarn 到 pnpm:JavaScript 包管理工具的演进之路
前端
星河丶1 小时前
React 的“组件即函数”理念
前端
星河丶1 小时前
什么是React中的副作用
前端·react.js
星河丶1 小时前
React 组件化的设计思想如何提升代码复用性
前端·react.js