验证码组件(子组件)
#Verification.vue
<template>
<div class="s-canvas">
<canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas>
</div>
</template>
<script>
export default {
name: "Verification",
//定义props数据可以通过父组件向子组件传递随机数让子组件渲染成验证码
props: {
identifyCode: {
type: String,
default: '1234'
},
fontSizeMin: {
type: Number,
default: 16
},
fontSizeMax: {
type: Number,
default: 40
},
backgroundColorMin: {
type: Number,
default: 180
},
backgroundColorMax: {
type: Number,
default: 240
},
colorMin: {
type: Number,
default: 50
},
colorMax: {
type: Number,
default: 160
},
lineColorMin: {
type: Number,
default: 40
},
lineColorMax: {
type: Number,
default: 180
},
dotColorMin: {
type: Number,
default: 0
},
dotColorMax: {
type: Number,
default: 255
},
contentWidth: {
type: Number,
default: 112
},
contentHeight: {
type: Number,
default: 38
}
},
methods: {
// 生成一个随机数
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
// 生成一个随机的颜色
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 + ')'
},
drawPic() {
let canvas = document.getElementById('s-canvas')
let ctx = canvas.getContext('2d')
ctx.textBaseline = 'bottom'
// 绘制背景
ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
// 绘制文字
for (let i = 0; i < this.identifyCode.length; i++) {
this.drawText(ctx, this.identifyCode[i], i)
}
this.drawLine(ctx)
this.drawDot(ctx)
},
drawText(ctx, txt, i) {
ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
var deg = this.randomNum(-45, 45)
// 修改坐标原点和旋转角度
ctx.translate(x, y)
ctx.rotate(deg * Math.PI / 180)
ctx.fillText(txt, 0, 0)
// 恢复坐标原点和旋转角度
ctx.rotate(-deg * Math.PI / 180)
ctx.translate(-x, -y)
},
drawLine(ctx) {
// 绘制干扰线
for (let i = 0; i < 8; i++) {
ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
ctx.beginPath()
ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
ctx.stroke()
}
},
drawDot(ctx) {
// 绘制干扰点
for (let i = 0; i < 100; i++) {
ctx.fillStyle = this.randomColor(0, 255)
ctx.beginPath()
ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)
ctx.fill()
}
}
},
watch: {
identifyCode() {
this.drawPic()
}
},
mounted() {
this.drawPic()
}
}
</script>
<style scoped>
</style>
注册组件(父组件)
关于验证码部分的片段
<a-form-item
v-bind="formItemLayout"
label="Captcha"
extra="We must make sure that your are a human."
>
<a-row :gutter="8">
<a-col :span="6">
<a-input v-decorator="[
'captcha',
{ rules: [{ required: true, message: '请输入验证码!' },{validator:validateCode,}] },
]"/>
</a-col>
<a-col :span="12" @click="refreshCode">
<Verification :identifyCode="identifyCode"></Verification>
</a-col>
</a-row>
</a-form-item>
父组件js部分
<script>
import Verification from "./Verification";
export default {
name: "register",
components:{
Verification
},
data() {
return {
identifyCodes: '1234567890',
identifyCode: '',
formItemLayout: {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
},
};
},
methods: {
//取随机数
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
//重置验证码方法
refreshCode() {
this.identifyCode = ''
this.makeCode(this.identifyCodes, 4)
},
//重置验证码具体实现
makeCode(o, l) {
for (let i = 0; i < l; i++) {
this.identifyCode += this.identifyCodes[
this.randomNum(0, this.identifyCodes.length)
]
}
},
//validator的验证方法,value为输入框输入的值,callback定义的是返回的提示。在antd的v-decorator表单验证中,callback()带值,则提交不了表单,比如这样callback('123')即时callback('')也不行。
validateCode(rule, value, callback) {
const identifyCode = this.identifyCode
if (identifyCode !== value) {
callback('请输入正确的验证码');
} else {
callback();
}
},
},
//保证每次刷新都进行验证码的更新
created() {
this.refreshCode()
}
}
</script>
效果
说明
该验证码因为用的是antd的v-decorator的数据验证,所以效果是在输入时就会有提示是否输入正确,而不是在提交表单之后才给提示。若是要后者的效果,选择用在form表单标签写数据验证规则。
实现思路
父组件创建一个随机值—>子组件接收值通过canvas 绘制验证码。
传值:子组件上建立props数据表
export default {
name: "Verification",
props: {
identifyCode: {
type: String,
default: '1234'
},
}
}
父组件在调用子组件时在其标签上用冒号加变量名引用传值:
<Verification :identifyCode="identifyCode"></Verification>//冒号里的identifyCode为要穿给子组件的数据
父组件向子组件传值参考:https://www.cnblogs.com/shengnan-2017/p/10419050.html
父组件完整代码
#register.vue
<template>
<a-form :form="form" class="register1" @submit="handleSubmit">
<a-form-item v-bind="formItemLayout" label="邮箱">
<a-input
v-decorator="[
'email',
{
rules: [
{
type: 'email',
message: 'The input is not valid E-mail!',
},
{
required: true,
message: 'Please input your E-mail!',
},
],
},
]"
/>
</a-form-item>
<a-form-item v-bind="formItemLayout" label="密码" has-feedback>
<a-input
v-decorator="[
'password',
{
rules: [
{
required: true,
message: '请输入密码!',
},
{
validator: validateToNextPassword,
},
],
},
]"
type="password"
/>
</a-form-item>
<a-form-item v-bind="formItemLayout" label="确认密码" has-feedback>
<a-input
v-decorator="[
'confirm',
{
rules: [
{
required: true,
message: '请确认您的密码!',
},
{
validator: compareToFirstPassword,
},
],
},
]"
type="password"
@blur="handleConfirmBlur"
/>
</a-form-item>
<a-form-item v-bind="formItemLayout">
<span slot="label">
昵称
<a-tooltip title="网络世界真真假假假假真真">
<a-icon type="question-circle-o" />
</a-tooltip>
</span>
<a-input
v-decorator="[
'nickname',
{
rules: [{ required: true, message: '请输入昵称!', whitespace: true }],
},
]"
/>
</a-form-item>
<a-form-item v-bind="formItemLayout" label="电话号码">
<a-input
v-decorator="[
'phone',
{
rules: [{ required: true, message: '请输入你的电话号码!' }],
},
]"
style="width: 100%"
>
<a-select
slot="addonBefore"
v-decorator="['prefix', { initialValue: '86' }]"
style="width: 70px"
>
<a-select-option value="86">
+86
</a-select-option>
<a-select-option value="87">
+87
</a-select-option>
</a-select>
</a-input>
</a-form-item>
<a-form-item
v-bind="formItemLayout"
label="Captcha"
extra="We must make sure that your are a human."
>
<a-row :gutter="8">
<a-col :span="6">
<a-input v-decorator="[
'captcha',
{ rules: [{ required: true, message: '请输入验证码!' },{validator:validateCode,}] },
]"/>
</a-col>
<a-col :span="12" @click="refreshCode">
<Verification :identifyCode="identifyCode"></Verification>
</a-col>
</a-row>
</a-form-item>
<a-form-item v-bind="tailFormItemLayout">
<a-checkbox v-decorator="['agreement', { valuePropName: 'checked' }]">
I have read the
<a href="">
agreement
</a>
</a-checkbox>
</a-form-item>
<a-form-item v-bind="tailFormItemLayout">
<a-button type="primary" html-type="submit" >
Register
</a-button>
</a-form-item>
</a-form>
</template>
<script>
import Verification from "./Verification";
export default {
name: "register",
components:{
Verification
},
data() {
return {
isDebugLogin: false,
confirmDirty: false,
identifyCodes: '1234567890',
identifyCode: '',
code:'',
autoCompleteResult: [],
formItemLayout: {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
},
tailFormItemLayout: {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
},
};
},
beforeCreate() {
this.form = this.$form.createForm(this, { name: 'register' });
},
methods: {
randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
refreshCode() {
this.identifyCode = ''
this.makeCode(this.identifyCodes, 4)
},
makeCode(o, l) {
for (let i = 0; i < l; i++) {
this.identifyCode += this.identifyCodes[
this.randomNum(0, this.identifyCodes.length)
]
}
},
handleSubmit(e) {
e.preventDefault();
this.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
},
handleConfirmBlur(e) {
const value = e.target.value;
this.confirmDirty = this.confirmDirty || !!value;
},
compareToFirstPassword(rule, value, callback) {
const form = this.form;
if (value && value !== form.getFieldValue('password')) {
callback('Two passwords that you enter is inconsistent!');
} else {
callback();
}
},
validateCode(rule, value, callback) {
const identifyCode = this.identifyCode
if (identifyCode !== value) {
callback('请输入正确的验证码');
} else {
callback();
}
},
validateToNextPassword(rule, value, callback) {
const form = this.form;
if (value && this.confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
},
},
created() {
this.refreshCode()
}
}
</script>
<style>
.register1{
margin: 0 auto;
padding-right: 20%;
}
</style>
```![](https://img-blog.csdnimg.cn/20201112103500887.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTM3Mjc4Mw==,size_16,color_FFFFFF,t_70#pic_center)
本例用到的ant design 组件,若需复现记得在main.js里面注册相应组件。
本文借鉴:https://www.jianshu.com/p/99c6e2f3e457