我们在做一个项目,登录注册页面是少不了的,为了人机校验,验证码也是必须的

我的这个项目获取验证码,前端发送一个随机四位数给后端,后端返回一张图片,前端渲染就可以

vue+element 获取验证码-LMLPHP

template代码:

 <el-form-item label="" prop="captcha_code">
<el-input
v-model="loginForm.captcha_code"
placeholder="验证码"
prefix-icon="lj-icon-yanzhengma"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
maxlength="4"
@keyup.enter.native="handleLogin"
style="float: left; width: 122px;"
></el-input>
<div class="captcha_code">
<img src="" ref="code" @click="changeCode">
</div>
</el-form-item>
<el-button
:loading="loading"
type="primary"
style="width: 100%;"
@click="handleLogin"
>登录</el-button>

data数据声明:

 data() {
return {
loginForm: {
username: "",
password: "",
captcha_key: "",
captcha_code: ""
},
}
}

mounted数据加载完执行方法:

mounted() { // 得到验证码图片 this.changeCode(); },

methods方法:

 getCaptchaKey() {
let captchaKey = Math.random()
.toString(36)
.substring(2);
return captchaKey;
},
changeCode() {
let captcha_key = this.getCaptchaKey();
this.loginForm.captcha_key = captcha_key;
this.$refs.code.setAttribute(
"src",
process.env.VUE_APP_API_URL +
"auth/get_captcha?captcha_key=" +
captcha_key
);
}
05-23 07:35