【vue】纯前端登录验证码实现记录
【寫在前面的話】
應項目安全需求,登錄驗證要新增驗證碼,下意識覺得是前端的工作,后來才發現前端驗證了個寂寞,真正安全的驗證碼驗證工作應該交給后臺來做,此是后話,先記錄一下純前端實現的驗證碼模塊。
【實現過程】
#1#-> 在/componets/下創建一個新的組件,命名為?VertifyCode.vue
<template><div class="s-canvas"><canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas></div> </template> <script>export default {name: 'VertifyCode',props: {identifyCode: {type: String,default: '1234'},fontSizeMin: {type: Number,default: 25},fontSizeMax: {type: Number,default: 30},backgroundColorMin: {type: Number,default: 255},backgroundColorMax: {type: Number,default: 255},colorMin: {type: Number,default: 0},colorMax: {type: Number,default: 160},lineColorMin: {type: Number,default: 100},lineColorMax: {type: Number,default: 255},dotColorMin: {type: Number,default: 0},dotColorMax: {type: Number,default: 255},contentWidth: {type: Number,default: 112},contentHeight: {type: Number,default: 31}},methods: {// 生成一個隨機數randomNum (min, max) {return Math.floor(Math.random() * (max - min) + min)},// 生成一個隨機的顏色randomColor (min, max) {const r = this.randomNum(min, max)const g = this.randomNum(min, max)const b = this.randomNum(min, max)return 'rgb(' + r + ',' + g + ',' + b + ')'},drawPic () {const canvas = document.getElementById('s-canvas')const 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'const x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))const 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 < 5; 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 < 80; 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>.s-canvas {height: 35px;padding: 2px;}.s-canvas canvas {/*margin-top: 1px;*//*margin-left: 8px;*/height: 35px;} </style>#2#-> 在登錄頁面 Login.vue,首先引入?VertifyCode.vue
<script>// 引入驗證碼組件import VertifyCode from '../components/VertifyCode' </script>在登錄頁面創建要渲染驗證碼的控件,這里采用了element-ui的el-form控件,用append的方式追加在input框之后
需要注意的是,組件名符合駝峰式命名規則,如這里是VertifyCode,引入組件的時候要寫vertify-code,這個名字轉換是默認的格式規則,不能亂寫。
<!-- 驗證碼 --> <el-form-item prop="vertify_code"><el-input v-model="loginForm.vertify_code" placeholder="驗證碼" prefix-icon="el-icon-key"><template slot="append"><div class="login-code" @click="refreshCode" title="看不清?點擊切換"><vertify-code :identifyCode="identifyCode"></vertify-code></div></template></el-input> </el-form-item>給驗證碼添加一個鼠標移上去自動變小手的圖標
<style lang="less" scoped>.login-code {cursor: pointer;margin: 0;} </style>?在<script>中注冊VertifyCode組件,并完善methods方法
<script>// 引入驗證碼組件import VertifyCode from '../components/VertifyCode'export default {name: 'Login',components: { VertifyCode }, // 注冊組件data () {return {// 驗證碼組件identifyCodes: 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789',identifyCode: '',// 登錄組件loginForm: {user_id: '',user_pswd: '',vertify_code: ''},loginFormRules: {// 驗證用戶名是否合法user_id: [{required: true,message: '請輸入工號',trigger: 'blur'},{min: 8,max: 8,message: '工號必須是8位字符',trigger: 'blur'}],// 驗證密碼是否合法user_pswd: [{required: true,message: '請輸入密碼',trigger: 'blur'},{min: 8,// max: 10,message: '密碼長度在8位字符以上',trigger: 'blur'}],// 驗證碼輸入是否正確vertify_code: [{required: true,message: '請輸入驗證碼',trigger: 'blur'},{ required: true, validator: this.validateCode, change: 'blur' }]}}},// mounted () {// this.identifyCode = ''// this.makeCode(this.identifyCodes, 4)// },methods: {// 表單【登錄】submitLogin (formName) {// 登錄之前進行表單驗證this.$refs[formName].validate(async (valid) => {// 驗證成功if (valid) {const { data: res } = await this.$http.post('/login', this.loginForm)if (res.meta.status === '200') {this.$message.success('登錄成功!')} else {this.$message.error('登錄失敗!請檢查用戶名和密碼輸入是否正確!' + res.meta.msg)}}})},// 表單【重置】resetLoginForm (formName) {// this.$refs.loginFormRef.resetFields()this.$refs[formName].resetFields()},// 驗證碼randomNum (min, max) {return Math.floor(Math.random() * (max - min) + min)},// 生成隨機驗證碼makeCode (o, l) {for (let i = 0; i < l; i++) {this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]}// console.log('identifyCode: ' + this.identifyCode)},// 驗證碼刷新refreshCode () {this.identifyCode = ''this.makeCode(this.identifyCodes, 4)},// 驗證碼輸入校驗validateCode (rule, value, callback) {if (value !== this.identifyCode) {callback(new Error('驗證碼驗證錯誤!請輸入正確的驗證碼!'))} else {callback()}}},created () {this.refreshCode()}} </script>【實現效果】
【參考】
vue實現隨機驗證碼功能?https://www.cnblogs.com/web-aqin/p/10796326.html
vue項目 - 基于canvas的數字驗證碼?https://www.jianshu.com/p/99c6e2f3e457
vue identify--驗證碼插件?https://www.jianshu.com/p/0ec53763dc4c
vue實現前端隨機驗證碼(兩種方法)https://www.cnblogs.com/Alioo/p/12792569.html
總結
以上是生活随笔為你收集整理的【vue】纯前端登录验证码实现记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mac电脑如何导入ps笔刷 ,Adobe
- 下一篇: Vuex-状态管理(24)