Vue实现验证码功能

创建js组件

链接:https://pan.baidu.com/s/19PXeSTNB-tWvOhIP7DYoHw 
提取码:5nk9

(需要改宽度和高度,修改_init方法中的宽和高)

2.2.1 引入组件

import { GVerify } from '../assets/js/verifyCode';

2.2.2 定义验证对象

data() {
    return{
      loginForm: {
        username: '',
        password: '',
        verifyCode:''
      },
      loginFormRuls: {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          verifyCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' }
            
          ]
      }
    }

2.2.3 初始化节点

<el-form-item  prop="icode" label-width='0'>    
          <el-row :gutter="10">
            <el-col :span="12"><el-input v-model="loginForm.verifyCode" placeholder="验证码" @keyup.enter.native="submitForm"></el-input></el-col>      
           <el-col :span="12">
            <div id="v_container"></div>
            </el-col>            
          </el-row>
        </el-form-item>

方式一,使用Notification弹窗提示验证码是否正确

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

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

2.2.4 验证输入的是否正确

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

login() {
      var that = this

   // 获取验证码
   var verifyCode = this.loginForm.verifyCode
   var verifyFlag = this.verifyCode.validate(verifyCode)
   if (!verifyFlag) {
    that.$notify.error({
     title: '系统提示',
     message: '验证码输入错误'
    })
    return;
   } else {
    that.$notify({
     title: '系统提示',
     message: '验证码输入正确',
     type: 'success'
    })
   }
      //  登录按钮的表单预验证
        this.$refs.loginFormRef.validate(async valid => {  
            const { data:res }  = await this.$http.post('login', this.loginForm)
            console.log(res)
            if(!valid) return
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success('登录成功') 
            window.sessionStorage.setItem('token',res.data.token)          
            this.$router.push('/home')
        })        
     
    }

完整代码:

html:

<template>
  <div class="hello">
    
    <div class='loginTable'>
      <el-row class="mflexBox">
      <el-col :span='13' class="loginImage">
        <img src="../assets/images/left.jpg" height="404" alt="">
      </el-col>
      <el-col  :sm="24" :xs="24" class="table loginForm">
      <span class="table_name"><h1 class="font20">商品管理</h1></span>
      <el-form :model="loginForm"  ref="loginFormRef" :rules="loginFormRuls"  label-width="80px" >
        <el-form-item prop="username" label-width='0' >          
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item  prop="password" label-width='0'>          
          <el-input prefix-icon="el-icon-lock" type="password" v-model="loginForm.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item  prop="icode" label-width='0'>    
          <el-row :gutter="10">
            <el-col :span="12"><el-input v-model="loginForm.verifyCode" placeholder="验证码" @keyup.enter.native="submitForm"></el-input></el-col>      
           <el-col :span="12">
            <div id="v_container"></div>
            </el-col>            
          </el-row>
        </el-form-item>
        
      </el-form>      
      <el-button class="submit" type="primary" @click="login()">登录</el-button>
      <el-button type="text" size="mini">忘记密码?</el-button>
      </el-col>
    </el-row>
    </div>
    
  </div>
</template>

js: 

<script>
import { GVerify } from '../assets/js/verifyCode';
export default {
  data() {
    return{
      loginForm: {
        username: '',
        password: '',
        verifyCode:''
      },
      loginFormRuls: {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
          ],
          verifyCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' }
            
          ]
      }
    }
  },
  methods: {   
   
    login() {
      var that = this

   // 获取验证码
   var verifyCode = this.loginForm.verifyCode
   var verifyFlag = this.verifyCode.validate(verifyCode)
   if (!verifyFlag) {
    that.$notify.error({
     title: '系统提示',
     message: '验证码输入错误'
    })
    return;
   } else {
    that.$notify({
     title: '系统提示',
     message: '验证码输入正确',
     type: 'success'
    })
   }
      //  登录按钮的表单预验证
        this.$refs.loginFormRef.validate(async valid => {  
            const { data:res }  = await this.$http.post('login', this.loginForm)
            console.log(res)
            if(!valid) return
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success('登录成功') 
            window.sessionStorage.setItem('token',res.data.token)          
            this.$router.push('/home')
        })        
     
    }
  },mounted () {
  this.verifyCode = new GVerify('v_container')
},
components:{
  Notification
}
}
</script>

js: 

<style lang="less" scoped>
@import '@/assets/css/main.less';
@import '@/assets/css/main.css';
@import '@/assets/css/indexMedia.css';
.hello{ display: flex; height: 100vh; flex-wrap: wrap; align-items: center; justify-content: center; background: url(../assets/images/login_bg.jpg) center center;
  h1{font-weight: normal; margin-bottom:50px; color: #5a93fe;}
  .loginTable{width:800px; }
.table{background:#fff; width:350px;  padding:22px 30px; }
  input{border-radius:50px;}
  .reset_pas{font-size: 12px;}
  .submit{background:linear-gradient(90deg, #19b4f1 0%, #0e73e8 100%) !important; width: 100%;}
  .reset_pas{margin-top: 20px; display: inline-block; color: #5a93fe;}
}

</style>

 今天觉得验证码提示的形式有点不舒服,所以改进了一下,不使用弹窗,现附上代码:

 

 

 1、rules书写规则:

verifyCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            {
            validator: (rule, value, callback) => {
              if (value !== '') {
                if (value !== this.checkVerifyCode.options.code) {
                  callback(new Error('验证码输入错误'))
                  return false
                } else {
                  callback()
                }
              }else{
                callback(new Error('请输入验证码'))
                  return false
              }
            },
            trigger: 'blur'
          }            
          ]

 2、mounted写法:

mounted () {
    
  this.checkVerifyCode = new GVerify('v_container')
  
}

 3、同时:components 中的 Notification 可以删除了 

开发的时候找到的,做个备忘,也分享给需要的伙伴。

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值