背景:在项目中,我们经常会遇到使用验证码的场景,有时候,我们会使用js的插件解决这个问题,有时候,会调用后台接口,根据后台返回的4个数字生成验证码。本文,我们将介绍后面一种方法。
一、html部分
<div class="policy-wire">
<div class="policy-line flex_bt">
<div class="flex_st yzmLabel">
<label class="yzmLabel">验证码</label>
<input placeholder="请输入验证码" v-model.number="policyBox.captcha" type="number"/>
</div>
<img :src="codeImg" class="img-code" @click="updateCode" title="点击换一张"/>
</div>
<span v-show="InfoErrorMsg.captcha.flag" class="errorMsg flex_st">
<img src="@/assets/images/warning.png" alt/>
{{errorArr[2]}}
</span>
</div>
二、js部分
<script>
/*eslint-disable*/
const {baseURL} = require("../js/interface");
export default{
created(){
//渲染验证码
this.updateCode();
},
methods:{
updateCode(){
//生成十位随机数
this.Num = "";
for(var i = 0;i < 10;i++){
this.Num += Math.floor(Math.random() * 10);
}
this.codeImg = baseURL + "captcha/formula-captcha?token=" + this.Num;
},
//查询检索
inquiry(){
this.showResult = false;
this.errorArr = [];
var resy = this.checkCell();
if(resy == false){
this.GLOBAL.showToast("请填写相关检索信息!");
return;
}
var dt = {};
this.GLOBAL.post(
"captcha/validate/formula-captcha?result=" +
this.policyBox.captcha + this.Num,dt,(res,sta) =>{
if(sta == 1){
this.InfoErrorMsg.captcha.flag = false;
this.inquiryResult();
}else if(sta == 0){
this.errorArr[2] = "验证码错误!";
this.InfoErrorMsg.captcha.flag = true;
this.updateCode(); //再次渲染验证码图片
return;
}
}
);
},
},
data(){
policyBox:{
captcha:""
},
InfoErrorMsg: {
captcha:{flag:false}
},
codeImg:"",//验证码
showResult: false,
Num:"",
errorArr:[],
}
};
</script>
三、css部分
.policy-wire{
border-top: 1px solid #f3f3f3;
}
.policy-line label {
font-size; 14px;
color: #333;
}
.policy-line input {
padding-left: 15px;
font-size: 14px;
color: #999;
}
.img-code {
width: 85px;
}
相关图片如下所示:
参考博客:Vue纯数字验证码 https://blog.csdn.net/weixin_41996632/article/details/86510542
vue项目经验:图形验证码接口get请求处理 https://blog.csdn.net/weixin_30785593/article/details/94860568