效果图
验证码组件
可以直接复制使用
<template>
<div>
<canvas id="myCanvas" style="width:100px;height:30px" @click="updatedra"></canvas>
</div>
</template>
<script>
export default {
name:'ValidCode',
data() {
return {
code: ''
}
},
mounted () {
this.createCode();
this.$emit('func',this.code)
},
methods: {
randomColor(min, max) {
let r = this.randomNum(min, max);
let g = this.randomNum(min, max);
let b = this.randomNum(min, max);
return 'rgb(' + r + ',' + g + ',' + b + ')';
},
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
},
createCode() {
this.code = '';
//验证码的长度
let codeLength = 4;
const checkCode = document.getElementById('myCanvas');
const codeChars = [];
// 验证码所需数字和字母的集合
for (let i = 0; i < 26; i++) {
if (i < 10) {
codeChars.push(String.fromCharCode(i + 48));
}
codeChars.push(String.fromCharCode(i + 97));
codeChars.push(String.fromCharCode(i + 65));
}
// 组合数字和字母
for (let i = 0; i < codeLength; i++) {
let charNum = Math.floor(Math.random() * 52);
this.code += codeChars[charNum];
}
if (checkCode) {
this.drawVerify(checkCode, this.code);
}
},
drawVerify(cEle, value) {
const [ctx, width, height] = [cEle.getContext('2d'), cEle.width, cEle.height];
// 清空画布
ctx.clearRect(0, 0, width, height);
// 绘制背景色
ctx.fillStyle = this.randomColor(180, 240);
ctx.fillRect(0, 0, width, height);
// 填充字体
ctx.font = '90px Arial';
ctx.fillStyle = this.randomColor(50, 130);
ctx.fillText(value, 60, 100);
// 绘制干扰线
for (var i = 0; i < 10; i++) {
ctx.strokeStyle = this.randomColor(40, 180);
ctx.beginPath();
ctx.moveTo(this.randomNum(0, width), this.randomNum(0, height));
ctx.lineTo(this.randomNum(0, width), this.randomNum(0, height));
ctx.stroke();
}
// 绘制干扰点
for (var i = 0; i < 30; i++) {
ctx.fillStyle = this.randomColor(0, 255);
ctx.beginPath();
ctx.arc(this.randomNum(0, width), this.randomNum(0, height), 1, 0, 2 * Math.PI);
ctx.fill();
}
},
updatedra(){
this.createCode();
this.$emit('func',this.code)
}
},
}
</script>
<style scoped>
#myCanvas{
cursor: pointer;
}
</style>
父组件使用说明
// 引用组件
import ValidCode from './validcode'
//获得验证码 方法
getCode(data){
this.validcode = data
},
//校验验证码 方法
validateCode(rule, value, callback){
if (!value) {
callback(new Error('请输入验证码!'));
}else{
if (this.validcode.toUpperCase() == value.toUpperCase()) {
callback();
} else {
callback(new Error("验证码不正确"));
}
}
},
// 使用antd form 中代码
<a-row>
<a-col :span="12">
<a-form-item
v-bind="tailFormItemLayout"
label="验证码"
labelAlign="left"
required >
<a-input
v-decorator="['code',
{ rules: [
{
validator: validateCode,
}] },
]"
placeholder="请输入验证码"
/>
</a-form-item>
</a-col>
<a-col :span="12" >
<div class="code-container">
<ValidCode @func="getCode" ref="child"/>
</div>
</a-col>
</a-row>