在我们进行登录的时候,为了保护系统的安全性,也是防止恶意进行登录,进入到后台盗取数据,因此我们在登录的环节进行一定的安全保护,提升系统安全等级。在此我们运用阿拉伯数字和英文字母进行4位数的验证码校验,当然也可以进行多位字符进行校验,在此我使用生成4位验证码进行校验
验证码:前端绑定后端生成得验证码图片,前端提交表单信息到后端进行验证,后端验证码存入session
一、环境准备:
我这里由于本机上的还是vue 2 所以这边还是vue2开发的,而且主要是好嫖组件,毕竟不是专业的前端。
这里的话由于某些原因,我这里使用的包管理是 cnpm
不为别的就为了安装的时候不会被雷到。
这里先装一个 vuex 用来管理状态,怎么装一条命令的事情。
二、功能展示:
三、项目结构:
四、验证码生成:
<template>
<div class="ValidCode disabled-select"
:style="`width:${width}; height:${height}`"
@click="refreshCode">
<span v-for="(item, index) in codeList"
:key="index"
:style="getStyle(item)">
{{item.code}}
</span>
</div>
</template>
<script>
export default {
name: "ValidCode",
model: {
prop: 'value',
event: 'input'
},
props: {
width: {
type: String,
default: '100px'
},
height: {
type: String,
default: '34px'
},
length: {
type: Number,
default: 4
}
},
data () {
return {
codeList: []
}
},
mounted () {
this.createdCode()
},
methods: {
refreshCode () {
this.createdCode()
},
createdCode () {
const len = this.length
const codeList = []
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
const charsLen = chars.length
// 生成
for (let i = 0; i < len; i++) {
const rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
codeList.push({
code: chars.charAt(Math.floor(Math.random() * charsLen)),
color: `rgb(${rgb})`,
fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
padding: `${[Math.floor(Math.random() * 10)]}px`,
transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
})
}
// 指向
this.codeList = codeList
// 将当前数据派发出去
this.$emit('input', codeList.map(item => item.code).join(''))
},
getStyle (data) {
return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
}
}
}
</script>
<style scoped >
.ValidCode{
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
span{
display: inline-block;
}
}
</style>
五、验证码使用:
1.首先需要解决的是登录的跨域问题,使用我们的axios进行解决:
import axios from 'axios'
import {serverIp} from "../../public/config";
const request = axios.create({
baseURL: `http://localhost:9090`, // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
if (user) {
config.headers['token'] = user.token; // 设置请求头
}
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
2.在需要的页面进行引入
<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
const Base64 = require('js-base64').Base64
export default {
name: "Login",
components: {
ValidCode
},
data() {
return {
form: {
sex: 1,
username: '',
password: '',
},
checked: false,
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur"},
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 1, max: 20, message: '长度在 6 到 11 个字符', trigger: 'blur'}
],
},
validCode: '',
}
},
}
</script>
3.验证码校验
<ek-form-item>
<div style="display: flex">
<el-input v-model="form.validCode" style="width: 60%" placeholder="请输入验证码" size="medium"></el-input>
<ValidCode @input="createValidCode" />
</div>
</ek-form-item>
export default {
name: "Login",
components: {
ValidCode
},
data() {
return {
form: {
sex: 1,
username: '',
password: '',
},
checked: false,
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur"},
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 1, max: 20, message: '长度在 6 到 11 个字符', trigger: 'blur'}
],
},
validCode: '',
}
},
}
4.完整代码
<template>
<div style="height: 100vh; overflow: hidden">
<div style="height: 50px;
line-height: 50px;
border-bottom: 2px solid var(--colorRed);
padding-left: 20px;
color: var(--colorRed)">
<b style="font-size: 24px;">xx宿舍</b>
<i style="margin-left: 20px">-- 只为更好的你</i>
</div>
<div style="width: 50%;
margin: 50px auto;
border-radius: 10px;
box-shadow: 0 0 10px -2px cornflowerblue;
display: flex">
<div style="flex: 1; padding: 50px 50px">
<img src="../assets/images/学习.png" alt="" style="width: 100%;">
</div>
<div style="flex: 1; padding: 20px">
<div class="form-toggle">
<b >账号登录</b>
</div>
<el-form ref="form" :model="form" size="normal" :rules="rules" >
<el-form-item prop="username" class="props">
<el-input placeholder="账号" clearable v-model="form.username" prefix-icon="el-icon-user" />
</el-form-item>
<el-form-item prop="password" class="props">
<el-input placeholder="密码" v-model="form.password" show-password prefix-icon="el-icon-lock" />
</el-form-item>
<ek-form-item>
<div style="display: flex">
<el-input v-model="form.validCode" style="width: 60%" placeholder="请输入验证码" size="medium"></el-input>
<ValidCode @input="createValidCode" />
</div>
</ek-form-item>
<el-form-item style="padding-top:15px">
<el-button type="primary" style="width: 100%" @click="login" round>登 录</el-button>
</el-form-item>
<!-- <el-form-item>-->
<div style="margin: 10px 0; text-align: right;">
<a href="/register" style="color: var(--colorRed)">立即注册</a>
</div>
<!-- <el-button style="width: 100%" @click="register" round>点击注册</el-button>-->
<!-- </el-form-item>-->
</el-form>
</div>
</div>
</div>
</template>
<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
const Base64 = require('js-base64').Base64
export default {
name: "Login",
components: {
ValidCode
},
data() {
return {
form: {
sex: 1,
username: '',
password: '',
},
checked: false,
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur"},
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 1, max: 20, message: '长度在 6 到 11 个字符', trigger: 'blur'}
],
},
validCode: '',
}
},
mounted () {
let username = localStorage.getItem('username')
if (username) {
this.form.username = localStorage.getItem('username')
this.form.password = Base64.decode(localStorage.getItem('password'))// base64解密
this.checked = true
}
},
created() {
sessionStorage.removeItem("user")
},
methods: {
register:function(){
this.$router.push("/register");
},
//接收验证码组件提交的4位验证码
createValidCode(data) {
this.validCode = data
},
login() {
this.$refs['form'].validate((valid) => {
if (valid) {
if (!this.form.validCode) {
this.$message.error("请填写验证码")
return
}
if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
this.$message.error("验证码错误")
return
}
request.post("/user/login", this.form).then(res => {
if (res.code === '200'){
// sessionStorage.setItem("user", JSON.stringify(res.data))//缓存用户信息
localStorage.setItem("user", JSON.stringify(res.data))
if (res.data.role === 'USER') {
this.$router.push("/")
} else {
this.$router.push("/mall/index")
}
this.$message({
type: "success",
message: "登录成功"
})
} else {
this.$message({
type: "error",
message: res.msg
})
}
})
}
});
},
}
}
</script>
<style scoped>
.form-toggle {
margin: 20px 0;
text-align: center
}
.form-toggle b {
font-size: 20px;
cursor: pointer;
}
</style>
附送
全局定义css并在main.js里面引入
import './assets/css/global.css'
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.ml-5 {
margin-left: 5px;
}
.ml-10 {
margin-left: 10px;
}
.mr-5 {
margin-right: 5px;
}
.pd-10 {
padding: 10px;
}
body {
margin: 0;
padding: 0;
font-size: 14px;
color: #666;
--colorRed: orangered;
}
a {
text-decoration: none;
}
⛵小结
以上就是对Vue实现路由导航简单的概述,使得我们的项目更加的趋于完美,也提升了我们对于编程的能力和思维!文章来源:https://www.toymoban.com/news/detail-499378.html
如果这篇文章有帮助到你,希望可以给作者点个赞👍,创作不易,如果有对后端技术、前端领域感兴趣的,也欢迎关注 ,我将会给你带来巨大的收获与惊喜💝💝💝!文章来源地址https://www.toymoban.com/news/detail-499378.html
到了这里,关于Vue实现验证码登录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!