vue中实现验证码

2022-07-14 12:36:38

目录

一, vue-puzzle-vcode插件

1、安装vue-puzzle-vcode

2,实现代码

3,效果图

二, vue2-verify

三,vue-monoplasty-slide-verify

 1,安装

2,实现

3,效果图

四、封装组件

五、基于svg-captcha(推荐)

六、原生js


 参考:node从入门到放弃系列之(10)图形验证功能_高素质车间工人的博客-CSDN博客

0,vue-monoplasty-slide-verify/

vue-monoplasty-slide-verify: 基于滑动式的验证码,免于字母验证码的繁琐输入用于网页注册或者登录

一, vue-puzzle-vcode插件

GitHub地址:beeworkshop/vue-puzzle-vcode

1、安装vue-puzzle-vcode

cnpm i -S vue-puzzle-vcode

2,实现代码

<template>
  <div>
    <Vcode :show="isShow" @success="success" @close="close" />
    <el-button @click="submit">登录</el-button>
  </div>
</template>

<script>
import Vcode from "vue-puzzle-vcode";
export default {
  data() {
    return {
      isShow: true // 验证码模态框是否出现
    };
  },
  components: {
    Vcode
  },
  methods: {
    submit() {
      this.isShow = true;
    },
    // 用户通过了验证
    success(msg) {
      this.isShow = false; // 通过验证后,需要手动隐藏模态框
    },
    // 用户点击遮罩层,应该关闭模态框
    close() {
      this.isShow = false;
    }
  }
};
</script>

3,效果图

此外,这里还有一些属性,比如宽,高等,见:beeworkshop/vue-puzzle-vcode

二, vue2-verify

GitHub:GitHub - mizuka-wu/vue2-verify: vue的验证码插件

vue2-verify的组件功能很全,包括5种验证功能,如下:

  1. 常规验证码picture 常规的验证码由数字和字母构成,用户输入不区分大小写,可变形成汉字验证。
  2. 运算验证码compute 运算验证码主要通过给出数字的加减乘运算,填写运算结果进行验证。
  3. 滑动验证码slide 通过简单的滑动即可完成验证,应用与移动端体验很好。
  4. 拼图验证码puzzle 拼图。
  5. 选字验证码pick 通过按顺序点选图中的汉字完成验证,ie浏览器要求9或以上。

如果需要定制化验证码,那么可以选择这个插件,如果对验证码要求不高,使用vue-puzzle-vcode更方便一点

三,vue-monoplasty-slide-verify

gitee地址:vue-monoplasty-slide-verify: 基于滑动式的验证码,免于字母验证码的繁琐输入用于网页注册或者登录

 1,安装

cnpm install -S vue-monoplasty-slide-verify

2,实现

// main.js
import Vue from 'vue';
import SlideVerify from 'vue-monoplasty-slide-verify';
Vue.use(SlideVerify);

// template
<slide-verify 
    ref="slideblock"
    @again="onAgain"
    @fulfilled="onFulfilled"
    @success="onSuccess"
    @fail="onFail"
    @refresh="onRefresh"
    :accuracy="accuracy"
    :slider-text="text"
></slide-verify>
<div>{{msg}}</div>

<button @click="handleClick">在父组件可以点我刷新哦</button>
// script
export default {
   name: 'App',
    data(){
        return {
            msg: '',
            text: '向右滑',
            // 精确度小,可允许的误差范围小;为1时,则表示滑块要与凹槽完全重叠,才能验证成功。默认值为5
            accuracy: 1,
        }
    },
    methods: {
        onSuccess(times){
           console.log('验证通过,耗时 +' +times + '毫秒');
            this.msg = 'login success, 耗时${(times / 1000).toFixed(1)}s'
        },
        onFail(){
            console.log('验证不通过');
            this.msg = ''
        },
        onRefresh(){
            console.log('点击了刷新小图标');
            this.msg = ''
        },
        onFulfilled() {
            console.log('刷新成功啦!');
        },
        onAgain() {
            console.log('检测到非人为操作的哦!');
            this.msg = 'try again';
            // 刷新
            this.$refs.slideblock.reset();
        },
        handleClick() {
        	// 父组件直接可以调用刷新方法
            this.$refs.slideblock.reset();
        },
    }
}

3,效果图

这个体验感觉不太好,尤其是刷新背景图时会有一段时间的空白,但好在它可以计算出验证过程的耗时

四、封装组件

不区分大小写

组件:ValidateCode.vue

<template>
  <canvas ref="canvas" @click="draw" width="140" height="40" style="cursor: pointer;"></canvas>
</template>
<script>
export default {
  data() {
    return {
      codes: [],
      ctx: "",
      colors: ["red", "yellow", "blue", "green", "pink", "black"],
      code_Len: 4
    };
  },
  mounted() {
    this.draw();
  },
  computed: {
    codeString() {
      let result = "";
      for (let i = 0; i < this.codes.length; i++) {
        result += this.codes[i];
      }
      return result.toUpperCase();
    }
  },
  watch: {
    codeString: function(newValue) {
      this.$emit("change", newValue);
    }
  },
  methods: {
    generateRandom() {
      this.codes = [];
      const chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
      const charsArr = chars.split("");

      for (let i = 0; i < this.code_Len; i++) {
        const num = Math.floor(Math.random() * charsArr.length);
        this.codes.push(charsArr[num]);
      }
    },
    draw() {
      this.generateRandom();
      this.drawText();
    },
    drawLine() {
      const lineNumber = 3; // 线条条数
      const lineX = 140;
      const lineY = 30; // 最大线条坐标
      for (let i = 0; i < lineNumber; i++) {
        this.ctx.strokeStyle = this.colors[Math.floor(Math.random() * 5)];
        this.ctx.beginPath();
        this.ctx.moveTo(
          Math.floor(Math.random() * lineX),
          Math.floor(Math.random() * lineY)
        );
        this.ctx.lineTo(
          Math.floor(Math.random() * lineX),
          Math.floor(Math.random() * lineY)
        );
        this.ctx.stroke();
      }
    },
    drawText() {
      const canvas = this.$refs["canvas"];
      this.ctx = canvas.getContext("2d");

      this.ctx.fillStyle = "#BFEFFF";
      this.ctx.fillRect(0, 0, 140, 40);
      this.ctx.font = "20px Verdana";

      let x = 15;

      for (let i = 0; i < this.code_Len; i++) {
        this.ctx.fillStyle = this.colors[Math.floor(Math.random() * 5)];
        this.ctx.fillText(this.codes[i], x, 25);
        x = x + 30;
      }

      this.drawLine();
    }
  }
};
</script>

使用:

<template>
  <div>
    <el-input v-model="inputVal" style="width:150px" clearable />
    <validate-code ref="ref_validateCode" @change="changeCode" />
    <el-button @click="compare()">比对</el-button>
    {{result}}
  </div>
</template>

<script>
import validateCode from "@/components/ValidateCode";
export default {
  components: {
    validateCode
  },
  data() {
    return {
      inputVal: "",
      checkCode: "",
      result: ""
    };
  },
  props: {},
  created() {},
  mounted() {},
  computed: {},
  methods: {
    changeCode(value) {
      this.checkCode = value;
    },
    compare() {
      if (this.inputVal.toUpperCase() === this.checkCode) {
        this.result = "比对成功";
      } else {
        this.result = "比对失败,请重新输入";
        this.inputVal = "";
        this.$refs["ref_validateCode"].draw();
      }
    }
  }
};
</script>

五、基于svg-captcha(推荐)

效果一:

效果二:

1、koa2中安装svg-captcha

cnpm i -S svg-captcha

2、koa2中生成验证码

const svgCaptcha = require('svg-captcha');

router.get('/getyzm', async (ctx, next) => {
  //create()创建字符验证码;createMathExpr()创建数学验证码
  const { data, text } = svgCaptcha.create({
    size: 4, //验证码长度
    fontSize: 45, //验证码字号
    noise: 2, //干扰线条数目
    width: 80, //宽度
    height: 40, //高度
    ignoreChars: "luv0o1i",//排除字符
    color: false, //验证码字符是否有颜色,默认是没有,但是如果设置了背景颜色,那么默认就是有字符颜色
    // background: '#ccc' //beijing
  })
  ctx.body = { data, text }
})

3、前端显示

<template>
   <div style="cursor:pointer" @click="getyzm()" v-html="codeyzm"></div>
</template>

<script>
export default {
  data() {
    return {
      codeyzm: "",
    };
  },
  methods: {
    async getyzm() {
      let { data } = await this.$axios.get("/api/getyzm");
      this.codeyzm = data.data;
    }
 }
};
</script>

六、原生js

html:

<input type="text" id="input1">
<input type="button" id="checkCode" class="code" style="width:60px"onclick="createCode()">
<a href="###" onclick="createCode()">看不清楚</a>
<input id="Button1" onclick="validate();" type="button" value="确定">

Js:

var code; //在全局 定义验证码
function createCode() {
    code = new Array();
    var codeLength = 4; //验证码的长度
    var checkCode = document.getElementById("checkCode");
    checkCode.value = "";
    var selectChar = new Array(2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    for (var i = 0; i < codeLength; i++) {
        var charIndex = Math.floor(Math.random() * 32);
        code += selectChar[charIndex];
    }
    if (code.length != codeLength) {
        createCode();
    }
    checkCode.value = code;
}

function validate() {
    var inputCode = document.getElementById("input1").value.toUpperCase();
    if (inputCode.length <= 0) {
        alert("请输入验证码!");
        return false;
    } else if (inputCode != code) {
        alert("验证码输入错误!");
        createCode();
        return false;
    } else {
        alert("成功!");
        return true;
    }
}

css:

.code {
	background-image:url(111.jpg);
	font-family:Arial,宋体;
	font-style:italic;
	color:green;
	border:0;
	padding:2px 3px;
	letter-spacing:3px;
	font-weight:bolder;
}
.unchanged {
	border:0;
}

运行结果:

随机验证码:0-9:

function createCode() {
    let code = "";
    let codeLength = 4; //验证码的长度
    let selectChar = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    for (let i = 0; i < codeLength; i++) {
        let charIndex = Math.floor(Math.random() * 10);
        code += selectChar[charIndex];
    }
    return code;
}
  • 作者:~疆
  • 原文链接:https://blog.csdn.net/qq_40323256/article/details/108165323
    更新时间:2022-07-14 12:36:38