在登录或者找回密码的过程中,经常会遇到防止机器人大量注册而使用验证码功能,在本项目中是由前端完成验证码功能.将这个封装为了一个组件,按需引用就可以了.
<template>
<div class="ValidCode disabled-select" title="点击切换" :style="`width:${width}; height:${height}`" @click="refreshCode">
<span v-for="(item, index) in codeList" :key="index" :style="getStyle(item)">{{item.code}}</span>
</div>
</template>
<script>
export default {
name: 'validCode',
props: {
width: {
type: String,
default: '100px'
},
height: {
type: String,
default: '40px'
},
length: {
type: Number,
default: 4
}
},
data () {
return {
codeList: []
}
},
mounted () {
this.createdCode()
},
methods: {
refreshCode () {
this.createdCode()
},
createdCode () {
let len = this.length,
codeList = [],
chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789',
charsLen = chars.length
// 生成
for (let i = 0; i < len; i++) {
let rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
codeList.push({
code: chars.charAt(Math.floor(Math.random() * charsLen)),
color: `rgb(${rgb})`,
fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
padding: `${[Math.floor(Math.random() * 10)]}px`,
transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
})
}
// 指向
this.codeList = codeList
// 将当前数据派发出去
this.$emit('update:value', codeList.map(item => item.code).join(''))
},
getStyle (data) {
return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
}
}
}
</script>
<style scoped lang="scss">
.ValidCode{
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
span{
user-select: none;
display: inline-block;
}
}
</style>
使用方法
<el-form class="forget-form" ref="forgetForm" :rules="rules" :model="form">
<el-form-item prop="username">
<el-input v-model="form.username" placeholder="请输入用户名">
<i slot="prefix" class="icon el-icon-user-solid"></i>
</el-input>
</el-form-item>
<el-form-item prop="sidentify">
<el-col :span="18">
<el-input clearable placeholder="请输入验证码" v-model="form.sidentify"></el-input>
</el-col>
<el-col :span="6">
<v-sidentify ref="sidentifyDom" :value.sync="validCode"></v-sidentify>
</el-col>
</el-form-item>
</el-form>
import Sidentify from "@/components/common/Sidentify"; // 引入验证码组件
components: {
"v-sidentify": Sidentify
},
data(){
let validateSidentify = (rule, sidentify, callback) => {
if (!sidentify || sidentify === "") {
callback(new Error("请输入验证码"));
} else if (sidentify.toLowerCase() !== this.validCode.toLowerCase()) {
this.$refs["sidentifyDom"].refreshCode();
callback(new Error("验证码输入有误!请重新输入"));
} else callback();
};
return {
validCode: '',
rules: {
sidentify: [{ validator: validateSidentify, trigger: "blur" }],
},
}
}
//格式什么的自己改下
ps:这个是由一位前端小姐姐同事写的,我只是觉得写的非常好,所以码下来,希望以后遇到这类问题的时候可以直接使用