需要的效果
dom
<el-form :model="formData" :rules="rules" ref="formData" label-width="0px">
<el-form-item prop="picLyanzhengma">
<el-input type="text" placeholder="请输入验证码" @blur="checkLpicma()" v-model="formData.picLyanzhengma"></el-input>
<input type="button" @click="createCode" class="verification1" v-model="checkCode"/>
</el-form-item>
<el-button :loading="isLogin" type="primary" v-on:click="login('formData')">登录</el-button>
</el-form>
script
<script>
export default {
data () {
var checkCodes = (rule, value, callback) => {
if (value == '') {
callback(new Error('请输入验证码'));
} else if (value.toUpperCase() != this.checkCode) {
callback(new Error('验证码不正确'));
} else {
callback();
}
};
return {
formData: {
picLyanzhengma: ''
},
checkCode: '',
rules: {
picLyanzhengma :\[
{ validator: checkCodes, trigger:'blur'}
\]
},
isLogin: false
}
},
methods: {
// 生成图片验证码
createCode(){
let code = "";
var codeLength = 4;//验证码的长度
var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z');//随机数
for(var i = 0; i < codeLength; i++) {
//循环操作
var index = Math.floor(Math.random()*36);//取得随机数的索引(0~35)
code += random\[index\];//根据索引取得随机数加到code上
}
this.checkCode = code;//把code值赋给验证码
},
// 失焦验证图和密码
checkLpicma(){
let that = this
this.formData.picLyanzhengma.toUpperCase();//取得输入的验证码并转化为大写
if(this.formData.picLyanzhengma == '') {
// 留空不刷
}else if(this.formData.picLyanzhengma.toUpperCase() != this.checkCode ) {
this.createCode();// 输错就刷新验证码
this.formData.picLyanzhengma = '';
}else {
return true;
}
},
login (formName) {
var that = this
this.$refs\[formName\].validate((valid) => {
if (valid) {
// 验证通过
} else {
return false
}
})
}
}
}
</script>
css
.verification1{
vertical-align: middle;
width: 70px;
background: #f9f9f9;
border: solid 1px #ddd;
color: blue;
height: 2rem;
}