Vue - some common tool classes

This article introduces some common tool classes

1. Verification code
As shown in the figure below, the general background management system will design a verification code when logging in. This verification code is generated by the front end. Click canvas to switch the verification code. The type of QR code is number or letter, which can be set as required,

1. js of verification code
As shown in the following figure, js of verification code is introduced first

The code of verifyCode is as follows. You can modify the length and width (width and height in the_init method), the type, color, interference line, etc. of the verification code as needed.

function GVerify (options) {/ / create a graphic verification code object and receive the options object as a parameter

this.options = { // Default options parameter value
    id: '', // Container Id
    canvasId: 'verifyCanvas', // ID of canvas
    width: '100', // Default canvas width
    height: '38', // Default canvas height
    type: 'number', // Default type of graphic verification code: blend type of numbers and letters, number: pure numbers, letter: pure letters
    code: ''
}

if (Object.prototype.toString.call(options) === '[object Object]') { // Judge the type of incoming parameter
    for (var i in options) { // Modify the default parameter value according to the passed in parameters
        this.options[i] = options[i]
    }
} else {
    this.options.id = options
}

this.options.numArr = '0,1,2,3,4,5,6,7,8,9'.split(',')
this.options.letterArr = getAllLetter()

this._init()
this.refresh()

}

GVerify.prototype = {

/** Version number**/
version: '1.0.0',

/** Initialization method**/
_init: function () {
    var con = document.getElementById(this.options.id)
    var canvas = document.createElement('canvas')
    // this.options.width = con.offsetWidth > 0 ? con.offsetWidth : '30'
    // this.options.height = con.offsetHeight > 0 ? con.offsetHeight : '30'
    this.options.width = '100'
    this.options.height = '38'
    canvas.id = this.options.canvasId
    canvas.width = this.options.width
    canvas.height = this.options.height
    canvas.style.cursor = 'pointer'
    canvas.innerHTML = 'Your browser version does not support canvas'
    con.appendChild(canvas)
    var parent = this
    canvas.onclick = function () {
        parent.refresh()
    }
},

/** Generate verification code**/
refresh: function () {
    this.options.code = '';
    var canvas = document.getElementById(this.options.canvasId)
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d')
    }
    ctx.textBaseline = 'middle'
    ctx.fillStyle = randomColor(180, 240)
    ctx.fillRect(0, 0, this.options.width, this.options.height)
    let txtArr = '';
    if (this.options.type === 'blend') { // Determine verification code type
        txtArr = this.options.numArr.concat(this.options.letterArr)
    } else if (this.options.type === 'number') {
        txtArr = this.options.numArr
    } else {
        txtArr = this.options.letterArr
    }
    for (var i = 1; i <= 4; i++) {
        var txt = txtArr[randomNum(0, txtArr.length)]
        this.options.code += txt
        ctx.font = randomNum(this.options.height / 2, this.options.height) + 'px SimHei' // Randomly generated font size
        ctx.fillStyle = randomColor(50, 160) // Randomly generated font color
        ctx.shadowOffsetX = randomNum(-3, 3)
        ctx.shadowOffsetY = randomNum(-3, 3)
        ctx.shadowBlur = randomNum(-3, 3)
        ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
        var x = this.options.width / 5 * i
        var y = this.options.height / 2
        var deg = randomNum(-30, 30)
        /** Set the rotation angle and coordinate origin**/
        ctx.translate(x, y)
        ctx.rotate(deg * Math.PI / 180)
        ctx.fillText(txt, 0, 0)
        /** Restore rotation angle and coordinate origin**/
        ctx.rotate(-deg * Math.PI / 180)
        ctx.translate(-x, -y)
    }
    /** Draw interference line**/
    for (let i = 0; i < 4; i++) {
        ctx.strokeStyle = randomColor(40, 180)
        ctx.beginPath()
        ctx.moveTo(randomNum(0, this.options.width), randomNum(0, this.options.height))
        ctx.lineTo(randomNum(0, this.options.width), randomNum(0, this.options.height))
        ctx.stroke()
    }
    /** Draw interference points**/
    for (let i = 0; i < this.options.width / 4; i++) {
        ctx.fillStyle = randomColor(0, 255)
        ctx.beginPath()
        ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI)
        ctx.fill()
    }
},

/** Verification code**/
validate: function (code) {
    code = code.toLowerCase()
    var v_code = this.options.code.toLowerCase()
    if (code == v_code) {
        return true
    } else {
        return false
    }
}

}
/Generate letter array/
function getAllLetter () {

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'
return letterStr.split(',')

}
/Generate a random number/
function randomNum (min, max) {

return Math.floor(Math.random() * (max - min) + min)

}
/Generate a random color/
function randomColor (min, max) {

var r = randomNum(min, max)
var g = randomNum(min, max)
var b = randomNum(min, max)
return 'rgb(' + r + ',' + g + ',' + b + ')'

}

export {

GVerify

}
Copy code
2. Login page
Reference tool class

import { GVerify } from '@/assets/js/verifyCode.js';
Copy code
canvas code of verification code

<el-form-item prop="verifyCode">

<div>
    <el-input v-model="loginForm.verifyCode" @keyup.enter.native="enterEvent($event,3)" class="code-input" placeholder="Please enter the verification code" maxlength="4"></el-input>
    <div id="canvas" width="100" height="38"></div>
</div>
<span class="red-color" v-if="codeErr">{{codeMsg}}</span>

</el-form-item>
Copy code
Verification rules of verification code

const validateCode = (rule, value, callback) => {

 let verifyFlag = this.verifyCode.validate(value);
 if (!verifyFlag) {
     callback(new Error('Verification code input error'));
 } else {
     callback()
 }

};
Copy code
Verification rules of verification code

loginRules: {
verifyCode: [

 { required: true, message: 'Verification code cannot be empty'},
 { validator: validateCode, trigger: 'change'}

]
Copy code
2: Returns an array of center points based on a set of coordinates [latitude, latitude]
It is mainly used to calculate the center point according to a group of coordinate points. When opening the map, the point is in the middle of the map

/**

  • Returns an array of center points based on a set of coordinates [latitude, latitude]
  • @param points
  • @returns {number[]}
    */

export function getPointsCenter(points) {

var point_num = points.length; // Number of coordinate points
var X = 0, Y = 0, Z = 0;
for(let i = 0; i < points.length; i++) {
    if (points[i] == '') {
        continue;
    }
    var lat, lng, x, y, z;
    lat = parseFloat(points[i].latitude) * Math.PI / 180;
    lng = parseFloat(points[i].longitude) * Math.PI / 180;
    x = Math.cos(lat) * Math.cos(lng);
    y = Math.cos(lat) * Math.sin(lng);
    z = Math.sin(lat);
    X += x;
    Y += y;
    Z += z;
}
X = X / point_num;
Y = Y / point_num;
Z = Z / point_num;
var tmp_lng = Math.atan2(Y, X);
var tmp_lat = Math.atan2(Z, Math.sqrt(X * X + Y * Y));
return [tmp_lat * 180 / Math.PI, tmp_lng * 180 / Math.PI];

}
Copy code
3: Calculate the zoom level from the raw data
It mainly calculates the zoom level of the map according to a group of coordinate points, so that all coordinates can be displayed in the visual area.

/**

  • Calculate the zoom level from the raw data
  • @param points
    */

export function getZoom(points){

if(points.length > 0){
    let maxLng = points[0].longitude;
    let minLng = points[0].longitude;
    let maxLat = points[0].latitude;
    let minLat = points[0].latitude;
    let res;
    for (let i = points.length - 1; i >= 0; i--) {
        res = points[i];
        if(res.longitude > maxLng) maxLng = res.longitude;
        if(res.longitude < minLng) minLng = res.longitude;
        if(res.latitude > maxLat) maxLat = res.latitude;
        if(res.latitude < minLat) minLat = res.latitude;
    }
    let zoom = ["50","100","200","500","1000","2000","5000","10000","20000","25000","50000","100000","200000","500000","1000000","2000000"];// Levels 18 to 3.
    let pointA = new window.TMap.LatLng(maxLat, maxLng);  // Create point coordinate A
    let pointB = new window.TMap.LatLng(minLat, minLng);  // Create point coordinate B
    let distance = window.TMap.geometry.computeDistance([pointA, pointB]).toFixed(1);  // Obtain the distance between two points and keep two decimal places
    for (let i = 0,zoomLen = zoom.length; i < zoomLen; i++) {
        if(zoom[i] - distance > 0){
            return 18-i+3;// The reason for the increase is that the map range is often more than 10 times the scale distance. So the level will increase by 3.
        }
    }
}

}
Copy code
The above is the recently used tools. I hope it will help you. Record it and review the old and know the new!!!

last
If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: https://gitee.com/ZhongBangKe... esteem it a favor!

Keywords: Vue.js

Added by geon on Wed, 05 Jan 2022 12:39:57 +0200