vue+Element实现登录随机验证码

验证码验证只是前端,无需后台交互
首先,创建一个identify.vue页面,用于写各种:随机数字/字母,随机颜色,干扰点/线

identify.vue

 
 



然后就是在你需要的页面

html代码只是简单的输入行,图片,加验证码替换
@keyup.enter.native="submitForm()是我登录时摁下Enter直接登录的方法可有可无,自己选择


     
     
    
    
     
看不清,换一张

然后就是script

首先引入SIdentify

import SIdentify from '../../components/page/identify.vue'

下面各种方法,验证及规则就直接写完了

export default {
	data: function() {
	/* 自定义验证码规则 */
   const validateVerifycode = (rule, value, callback) => {
    if (value === '') {
     callback(new Error('请输入验证码'))
    } else if (value !== this.identifyCode) {
     console.log('validateVerifycode:', value);
     callback(new Error('验证码不正确!'))
    } else {
     callback()
    }
   }
	return {
		identifyCodes: '1234567890abcdefghijklmnopqrstuvwxyz',
  		identifyCode: '',
  		rules:{
  		verifycode: [{
      required: true,
      trigger: 'blur',
      validator: validateVerifycode,
     }]
			}
		};
	},
	components:{
	SIdentify
	},
	mounted(){
	this.identifyCode='';
	this.makeCode(this.identifyCodes,4);
	disableBrowserBack();
	 history.pushState(null, null, document.URL);
	  if (window.history && window.history.pushState) {
            $(window).on('popstate', function (){
                window.history.pushState('forward', null, '');
                window.history.forward(1);
           });
            window.history.pushState('forward', null, '');  //在IE中必须得有这两行
       window.history.forward(1);
	},
	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)]
    }
    console.log(this.identifyCode)
    /* alert(this.identifyCode) */
   }
	}
}

到这就已经完成了,还可以添加css样式完美一下

 .identifybox {
  display: flex;
  justify-content: space-between;
  margin-top: 7px;
 }

验证码分享就这么多了,O(∩_∩)O

你可能感兴趣的:(vue+Element实现登录随机验证码)