纯前端登录校验码组件封装

说明:

vue-monoplasty-slide-verify依赖为拖住验证需要,如只是用常规匹配验证或者运算验证可不需要,删除组件中的 代码逻辑即可。
  • 所需依赖:
npm install -S vue-monoplasty-slide-verify
  • 引入
// main.js
import slideVerify from "vue-monoplasty-slide-verify";
Vue.use(slideVerify);

  • 组件代码:
<template>
  <div>
    <div class="s-canvas" @click="createdCode" v-if="type != 'slide'">
      <canvas
        :id="domId"
        :width="contentWidth"
        :height="contentHeight"
      ></canvas>
    </div>
    <div :class="[show ? 'popContainer' : '']" v-if="type == 'slide'">
      <slideVerify
        v-if="show"
        :l="42"
        :r="10"
        :w="310"
        :h="155"
        :imgs="imgs"
        slider-text="向右滑动解锁"
        @success="onSuccess"
        @fail="onFail"
        @refresh="onRefresh"
      ></slideVerify>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    fontSizeMin: {
      type: Number,
      default: 25,
    },
    fontSizeMax: {
      type: Number,
      default: 30,
    },
    contentWidth: {
      type: Number,
      default: 120,
    },
    contentHeight: {
      type: Number,
      default: 34,
    },
    // 常规验证码picture ,运算验证码compute,滑动验证码slide
    type: {
      type: String,
      default: "slide",
    },
    identifyCodes: {
      type: String,
      default: "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789",
    },
    show: {
      type: Boolean,
      default: false,
    },
    imgs: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      identifyCode: "",
    };
  },
  mounted() {
    if (this.type != "slide") {
      this.createdCode();
    }
  },
  created() {
    this.domId = `s-canvas${this.type}`;
  },
  methods: {
    // 生成4个随机数
    createdCode() {
      const len = 4;
      const codeList = [];
      var emitValue = null;
      if (this.type == "picture") {
        let length = this.identifyCodes.length;
        for (let i = 0; i < len; i++) {
          codeList.push(
            this.identifyCodes.charAt(Math.floor(Math.random() * length))
          );
        }
        emitValue = codeList.join("");
      } else if (this.type == "compute") {
        const chars = "0123456789";
        var count = "+×-";
        const charsLen = chars.length;
        var countIndex = Math.floor(Math.random() * 3);
        count = count.charAt(countIndex);
        for (let i = 0; i < len; i++) {
          if (i == 1) {
            codeList.push(count);
          } else if (i == 3) {
            codeList.push("=");
          } else {
            codeList.push(chars.charAt(Math.floor(Math.random() * charsLen)));
          }
        }
        var code = 0;
        if (countIndex == 0) {
          code = parseInt(codeList[0]) + parseInt(codeList[2]);
        } else if (countIndex == 1) {
          code = parseInt(codeList[0]) * parseInt(codeList[2]);
        } else {
          code = parseInt(codeList[0]) - parseInt(codeList[2]);
        }
        emitValue = code;
      }
      console.log(emitValue);
      console.log(codeList);
      this.identifyCode = codeList.join("");
      this.$emit("verifyResult", emitValue);
      this.drawPic();
    },

    // 生成一个随机数
    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(this.domId);
      const ctx = canvas.getContext("2d");
      ctx.textBaseline = "bottom";
      // 绘制背景
      ctx.fillStyle = this.randomColor(255, 255);
      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(0, 160);
      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(100, 255);
        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();
      }
    },

    onSuccess() {
      this.$emit("verifyResult", true);
      this.show = false;
    },
    onFail() {
      this.$emit("verifyResult", false);
    },
    onRefresh() {},
  },
};
</script>
<style scoped lang="scss">
.s-canvas {
  height: 38px;
  cursor: pointer;
}
.s-canvas canvas{
  margin-top: 1px;
  margin-left: 8px;
}
.popContainer{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.1);
  z-index: 99999;
  display: flex;
  align-items: center;
  justify-content: center;
  /deep/.slide-verify-slider{
      margin-top:0;
    }
}
</style>
  • 引用代码
<template>
  <div>
    <el-input v-model="inputs1">
      <span slot="suffix">
        <verificationCode
          @verifyResult="verifyResult"
          type="picture"
        ></verificationCode>
      </span>
    </el-input>

    <el-input v-model="inputs">
      <span slot="suffix">
        <verificationCode
          @verifyResult="verifyResult"
          type="compute"
        ></verificationCode>
      </span>
    </el-input>

    <verificationCode
      @verifyResult="verifyResult"
      :show="show"
      type="slide"
      :imgs="imgs"
    ></verificationCode>
    <el-button @click="verifiShow" v-show="!show">显示验证</el-button>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    //这里存放数据
    return {
      inputs: "",
      show: false,
      inputs1: "",
      imgs: [
        require("@/assets/图片1.png"),
        require("@/assets/图片2.png"),
        require("@/assets/图片3.png"),
      ],
    };
  },
  methods: {
    verifyResult(val) {
   	// 验证码返回值,滑动验证码返回true/false
      if (val) {
        this.show = false;
      }
    },
    verifiShow() {
      this.show = !this.show;
    },
  },
};
</script>

props中的参数

参数名类型说明
fontSizeMinNumber常规校验和运算验证,文字最小px
fontSizeMaxNumber常规校验和运算验证,文字最大px
contentWidthNumber常规校验和运算验证,canvas画布宽度
contentHeightNumber常规校验和运算验证,canvas画布高度
identifyCodesString常规校验和运算验证,可显示内容
typeString常规验证码picture ,运算验证码compute,滑动验证码slide
showBoolean控制滑动验证码显示隐藏
imgsArray滑动验证码背景图list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值