前端添加登录验证码 vue
组件 ValidCode.vue
<template>
<div class="validCode-wrapper" @click="refreshCode">
<span class="tbfont" :style="code.style" v-for="(code,index) in codeList" :key='index'>
{{code.char || code}}
</span>
</div>
</template>
<script>
export default {
name: 'ValidCode',
props: {
length: {
type: Number,
default: 4
},
hasColor: {
type: Boolean,
default: false
},
codeColor: {
type: String,
default: 'inherit'
}
},
data() {
return {
codeChose: '',
codeLength: 4,
codeList: []
}
},
created() {},
mounted() {
this.createdCode()
},
methods: {
refreshCode() {
this.createdCode()
},
createdCode() {
const code_chars = [1, 2, 3, 4, 5, 6, 7, 8, 9, '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'
];
this.codeList = []
this.codeChose = ''
for (let i = 0; i < this.codeLength; i++) {
let rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
let charNum = Math.floor(Math.random() * 52)
let tmpStyle = (charNum % 2 == 0) ? "font-style:italic;margin-right: 4px;" : "font-weight:bolder;";
tmpStyle += (Math.floor(Math.random() * 2) == 1) ? "font-weight:bolder;" : "";
tmpStyle += "transform: " + `rotate(${Math.floor(Math.random() * 50) - Math.floor(Math.random() * 50)}deg)` + ";";
tmpStyle += this.hasColor ? "color:" + `rgb(${rgb})` + ";" : "color: " + this.codeColor + ";";
this.codeChose += code_chars[charNum]
this.codeList.push({
style: tmpStyle,
char: code_chars[charNum]
})
}
},
getStyle(data) {
return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
}
}
}
</script>
<style scoped lang="scss">
.validCode-wrapper {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
span {
display: inline-block;
}
.tbfont {
font-size: 25px;
}
}
</style>
登录页引用 login.vue
// html
<el-form-item>
<ValidCode
ref="validCode"
:length="4"
:has-color="false"
code-color="#1f01f4"
/>
</el-form-item>
// js
import ValidCode from '@/components/ValidCode/ValidCode.vue'
components: {
ValidCode
}