vue.js怎么实现验证码

 4638

vue实现验证码的方法:1、创建js组件;2、引入组件;3、定义验证对象;4、初始化节点;5、通过validate()方法验证输入的是否正确即可。


vue.js怎么实现验证码


Vue实现验证码功能,具体内容如下


1、效果


vue.js怎么实现验证码


2、代码

2.1 创建js组件


vue.js怎么实现验证码


内容(可直接粘贴过去,需要改宽度和高度,修改_init方法中的宽和高)

  1. function GVerify (options) { // 创建一个图形验证码对象,接收options对象为参数
  2.   this.options = { // 默认options参数值
  3.     id: '', // 容器Id
  4.     canvasId: 'verifyCanvas', // canvas的ID
  5.     width: '80', // 默认canvas宽度
  6.     height: '30', // 默认canvas高度
  7.     type: 'number', // 图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
  8.     code: ''
  9.   }
  10.   
  11.   if (Object.prototype.toString.call(options) === '[object Object]') { // 判断传入参数类型
  12.     for (var i in options) { // 根据传入的参数,修改默认参数值
  13.       this.options[i] = options[i]
  14.     }
  15.   } else {
  16.     this.options.id = options
  17.   }
  18.   
  19.   this.options.numArr = '0,1,2,3,4,5,6,7,8,9'.split(',')
  20.   this.options.letterArr = getAllLetter()
  21.   
  22.   this._init()
  23.   this.refresh()
  24. }
  25.   
  26. GVerify.prototype = {
  27.   /** 版本号**/
  28.   version: '1.0.0',
  29.   
  30.   /** 初始化方法**/
  31.   _init: function () {
  32.     var con = document.getElementById(this.options.id)
  33.     var canvas = document.createElement('canvas')
  34.     // this.options.width = con.offsetWidth > 0 ? con.offsetWidth : '30'
  35.     // this.options.height = con.offsetHeight > 0 ? con.offsetHeight : '30'
  36.     this.options.width = '160'
  37.     this.options.height = '50'
  38.     canvas.id = this.options.canvasId
  39.     canvas.width = this.options.width
  40.     canvas.height = this.options.height
  41.     canvas.style.cursor = 'pointer'
  42.     canvas.innerHTML = '您的浏览器版本不支持canvas'
  43.     con.appendChild(canvas)
  44.     var parent = this
  45.     canvas.onclick = function () {
  46.       parent.refresh()
  47.     }
  48.   },
  49.   
  50.   /** 生成验证码**/
  51.   refresh: function () {
  52.     var canvas = document.getElementById(this.options.canvasId)
  53.     if (canvas.getContext) {
  54.       var ctx = canvas.getContext('2d')
  55.     }
  56.     ctx.textBaseline = 'middle'
  57.   
  58.     ctx.fillStyle = randomColor(180, 240)
  59.     ctx.fillRect(0, 0, this.options.width, this.options.height)
  60.   
  61.     if (this.options.type === 'blend') { // 判断验证码类型
  62.       var txtArr = this.options.numArr.concat(this.options.letterArr)
  63.     } else if (this.options.type === 'number') {
  64.       var txtArr = this.options.numArr
  65.     } else {
  66.       var txtArr = this.options.letterArr
  67.     }
  68.   
  69.     for (var i = 1; i <= 4; i++) {
  70.       var txt = txtArr[randomNum(0, txtArr.length)]
  71.       this.options.code += txt
  72.       ctx.font = randomNum(this.options.height / 2, this.options.height) + 'px SimHei' // 随机生成字体大小
  73.       ctx.fillStyle = randomColor(50, 160) // 随机生成字体颜色
  74.       ctx.shadowOffsetX = randomNum(-3, 3)
  75.       ctx.shadowOffsetY = randomNum(-3, 3)
  76.       ctx.shadowBlur = randomNum(-3, 3)
  77.       ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
  78.       var x = this.options.width / 5 * i
  79.       var y = this.options.height / 2
  80.       var deg = randomNum(-30, 30)
  81.       /** 设置旋转角度和坐标原点**/
  82.       ctx.translate(x, y)
  83.       ctx.rotate(deg * Math.PI / 180)
  84.       ctx.fillText(txt, 0, 0)
  85.       /** 恢复旋转角度和坐标原点**/
  86.       ctx.rotate(-deg * Math.PI / 180)
  87.       ctx.translate(-x, -y)
  88.     }
  89.     /** 绘制干扰线**/
  90.     for (var i = 0; i < 4; i++) {
  91.       ctx.strokeStyle = randomColor(40, 180)
  92.       ctx.beginPath()
  93.       ctx.moveTo(randomNum(0, this.options.width), randomNum(0, this.options.height))
  94.       ctx.lineTo(randomNum(0, this.options.width), randomNum(0, this.options.height))
  95.       ctx.stroke()
  96.     }
  97.     /** 绘制干扰点**/
  98.     for (var i = 0; i < this.options.width / 4; i++) {
  99.       ctx.fillStyle = randomColor(0, 255)
  100.       ctx.beginPath()
  101.       ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI)
  102.       ctx.fill()
  103.     }
  104.   },
  105.   
  106.   /** 验证验证码**/
  107.   validate: function (code) {
  108.     var code = code.toLowerCase()
  109.     var v_code = this.options.code.toLowerCase()
  110.     if (code == v_code) {
  111.       return true
  112.     } else {
  113.       return false
  114.     }
  115.   }
  116. }
  117. /** 生成字母数组**/
  118. function getAllLetter () {
  119.   var letterStr = '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,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'
  120.   return letterStr.split(',')
  121. }
  122. /** 生成一个随机数**/
  123. function randomNum (min, max) {
  124.   return Math.floor(Math.random() * (max - min) + min)
  125. }
  126. /** 生成一个随机色**/
  127. function randomColor (min, max) {
  128.   var r = randomNum(min, max)
  129.   var g = randomNum(min, max)
  130.   var b = randomNum(min, max)
  131.   return 'rgb(' + r + ',' + g + ',' + b + ')'
  132. }
  133.   
  134. export {
  135.   GVerify
  136. }

2.2 登录页面

2.2.1 引入组件

  1. [....<script>]
  2.   
  3. import { GVerify } from '../../static/js/verifyCode';
  4.   
  5. [export default { ....]

2.2.2 定义验证对象

注意 verifyCode

  1. data: function () {
  2.   return {
  3.     title: '若晨后台管理系统',
  4.     ruleForm: {
  5.       username: '',
  6.       password: '',
  7.       verifyCode: ''
  8.     },
  9.     rules: {
  10.       username: [
  11.         { required: true, message: '请输入用户名', trigger: 'blur' }
  12.       ],
  13.       password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  14.       verifyCode: [
  15.         { required: true, message: '请输入验证码', trigger: 'blur' }
  16.       ]
  17.     },
  18.     verifyCode: null
  19.   }
  20. },

2.2.3 初始化节点

  1. <el-form-item prop="verifyCode" class="verifyCodeItemCss">
  2.     <el-input class="verify_css" placeholder="请输入4位验证码" v-model="ruleForm.verifyCode" @keyup.enter.native="submitForm('ruleForm')"></el-input>
  3.     <!--关键 ↓-->
  4.     <div id="v_container"></div>
  5. </el-form-item>

mounted方法中初始化 'v_container' 为div的id

  1. mounted () {
  2.   this.verifyCode = new GVerify('v_container')
  3. }

2.2.4 验证输入的是否正确

通过在data中定义的verifyCode对象的validate()方法,如果输入正确返回true 错误返回 false

  1. var that = this
  2.   
  3. // 获取验证码
  4. var verifyCode = this.ruleForm.verifyCode
  5. var verifyFlag = this.verifyCode.validate(verifyCode)
  6. if (!verifyFlag) {
  7.   that.$notify.error({
  8.     title: '系统提示',
  9.     message: '验证码输入错误'
  10.   })
  11.   return;
  12. } else {
  13.   that.$notify({
  14.     title: '系统提示',
  15.     message: '验证码输入正确',
  16.     type: 'success'
  17.   })
  18. }


3、全部页面代码

  1. <template>
  2.   <div class="login-wrap">
  3.     <div class="video-bg">
  4.       <video muted="" data-autoplay="" loop="" autoplay="" src="https://gss3.baidu.com/6LZ0ej3k1Qd3ote6lo7D0j9wehsv/tieba-movideo/65886292_9687ec67dfc37bfbf847d82b6b52a276_96e56b0f4bfc.mp4" class="video-tvc" id="video-tvc" data-object-fit="">
  5.       </video>
  6.     </div>
  7.     <div class="ms-title">{{title}}</div>
  8.     <div class="ms-login">
  9.       <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
  10.         <el-form-item prop="username">
  11.           <el-input v-model="ruleForm.username" placeholder="请输入账号"></el-input>
  12.         </el-form-item>
  13.         <el-form-item prop="password">
  14.           <el-input type="password" placeholder="请输入密码" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
  15.         </el-form-item>
  16.         <el-form-item prop="verifyCode" class="verifyCodeItemCss">
  17.           <el-input class="verify_css" placeholder="请输入4位验证码" v-model="ruleForm.verifyCode" @keyup.enter.native="submitForm('ruleForm')"></el-input>
  18.           <div id="v_container"></div>
  19.         </el-form-item>
  20.         <div class="login-btn">
  21.           <el-button class="loginBtn" type="primary" @click="submitForm('ruleForm')">登录</el-button>
  22.         </div>
  23.         <!--<p style="font-size:12px;line-height:30px;color:#999;">Tips : 用户名和密码随便填。</p>-->
  24.       </el-form>
  25.     </div>
  26.   </div>
  27. </template>
  28.   
  29. <script>
  30. import { GVerify } from '../../static/js/verifyCode';
  31. export default {
  32.   data: function () {
  33.     return {
  34.       title: '若晨后台管理系统',
  35.       ruleForm: {
  36.         username: '',
  37.         password: '',
  38.         verifyCode: ''
  39.       },
  40.       rules: {
  41.         username: [
  42.           { required: true, message: '请输入用户名', trigger: 'blur' }
  43.         ],
  44.         password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  45.         verifyCode: [
  46.           { required: true, message: '请输入验证码', trigger: 'blur' }
  47.         ]
  48.       },
  49.       verifyCode: null
  50.     }
  51.   },
  52.   mounted () {
  53.     // 随机播放帧数
  54.     this.videoCut()
  55.   
  56.     this.verifyCode = new GVerify('v_container')
  57.   },
  58.   methods: {
  59.     submitForm (formName) {
  60.       var that = this
  61.   
  62.       // 获取验证码
  63.       var verifyCode = this.ruleForm.verifyCode
  64.       var verifyFlag = this.verifyCode.validate(verifyCode)
  65.       if (!verifyFlag) {
  66.         that.$notify.error({
  67.           title: '系统提示',
  68.           message: '验证码输入错误'
  69.         })
  70.         return;
  71.       } else {
  72.         that.$notify({
  73.           title: '系统提示',
  74.           message: '验证码输入正确',
  75.           type: 'success'
  76.         })
  77.       }
  78.   
  79.       this.$refs[formName].validate(valid => {
  80.         if (valid) {
  81.           // 判断是否登录成功  
  82.           let param = {
  83.             userName: that.ruleForm.username,
  84.             passWord: that.ruleForm.password
  85.           }
  86.   
  87.           // this.axios.post(this.$service.user.USER_LOGIN_API.url,param).then(res=>{
  88.           //   console.log("请求成功",res)
  89.           //   if(res.data.data != undefined){
  90.           //     that.$notify({
  91.           //       title: '系统提示',
  92.           //       message: '登录成功',
  93.           //       type:"success"
  94.           //     });
  95.           //           // 存local
  96.           //     localStorage.setItem('ms_username',res.data.data.userNickName);
  97.           //     localStorage.setItem('token',res.data.data.id);
  98.           //     self.$router.push('/index');
  99.           //   }else{
  100.           //     that.$notify.error({
  101.           //     title: '系统提示',
  102.           //     message: '用户账户密码输出错误'
  103.           //     });
  104.           //   }
  105.   
  106.           localStorage.setItem('ms_username', 'admin')
  107.           localStorage.setItem('token', 'admin')
  108.           that.$router.push('/index')
  109.         } else {
  110.           console.log('error submit!!')
  111.           return false
  112.         }
  113.       })
  114.     },
  115.   
  116.     videoCut () {
  117.       $('video').on('loadedmetadata', function (event) {
  118.         var duration = Math.ceil(this.duration)
  119.         this.currentTime = Math.round(Math.random() * duration)
  120.       })
  121.     }
  122.   }
  123. }
  124. </script>
  125.   
  126.   
  127. <style scoped>
  128. .verify_css {
  129.   width: 45%;
  130. }
  131.   
  132. .login-wrap {
  133.   position: relative;
  134.   width: 100%;
  135.   height: 100%;
  136. }
  137. .ms-title {
  138.   position: absolute;
  139.   top: 50%;
  140.   width: 100%;
  141.   margin-top: -230px;
  142.   text-align: center;
  143.   font-size: 30px;
  144.   color: #fff;
  145. }
  146.   
  147. .ms-login {
  148.   position: absolute;
  149.   left: 50%;
  150.   top: 50%;
  151.   width: 300px;
  152.   height: 13rem;
  153.   margin: -150px 0 0 -190px;
  154.   padding: 40px;
  155.   border-radius: 6%;
  156.   background: #fff;
  157.   box-shadow: -2px -2px 17px 1px #1e9fff;
  158. }
  159. .login-btn {
  160.   text-align: center;
  161. }
  162. .login-btn button {
  163.   width: 100%;
  164.   height: 36px;
  165. }
  166. .video-bg {
  167.   min-width: 100%;
  168.   min-height: 100%;
  169.   width: 100%;
  170.   height: 100%;
  171.   opacity: 0.9;
  172. }
  173. video {
  174.   width: 100%;
  175.   height: 100%;
  176.   object-fit: cover;
  177.   /* opacity: 0.6; */
  178. }
  179.   
  180. .loginBtn:hover {
  181.   box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.3), 0px 0px 20px rgba(0, 0, 0, 0.1) inset;
  182. }
  183.   
  184. #v_container {
  185.   width: auto;
  186.   height: auto;
  187.   display: inline-flex;
  188.   position: relative;
  189.   top: 1rem;
  190.   margin-top: -2rem;
  191. }
  192. </style>


TAG标签:
本文网址:https://www.zztuku.com/index.php/detail-9819.html
站长图库 - vue.js怎么实现验证码
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐