安装依赖
npm install jsencrypt --save
局部引入
import JSEncrypt from 'jsencrypt/bin/jsencrypt';
登录页面index.vue
<template>
<div class="loginbody">
<div class="logindata">
<div class="logintext">
<h2>Welcome</h2>
</div>
<div class="formdata">
<el-form ref="form" :model="form" :rules="rules">
<el-form-item prop="username">
<el-input v-model="form.username" clearable placeholder="请输入账号"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="form.password" clearable placeholder="请输入密码" show-password></el-input>
</el-form-item>
</el-form>
</div>
<div class="tool">
<el-checkbox v-model="checked" @change="remember">记住密码</el-checkbox>
</div>
<div class="butt">
<el-button type="primary" @click.native.prevent="login('form')">登录</el-button>
</div>
</div>
</div>
</div>
</template>
<script>
import JSEncrypt from 'jsencrypt/bin/jsencrypt';
export default {
data() {
return {
form: {
username: "",
password: "",
},
pbkey: "",
checked: true,
rules: {
username: [{
required: true,
message: "请输入用户名",
trigger: "blur"
}],
password: [{
required: true,
message: "请输入密码",
trigger: "blur"
}],
},
};
},
mounted() {
// 是否记住密码
if (localStorage.getItem("emisLoginInfo")) {
this.form = JSON.parse(localStorage.getItem("emisLoginInfo"))
this.checked = true;
}
},
methods: {
// 点击登录按钮
login(form) {
this.$refs[form].validate((valid) => {
if (valid) {
// 表单校验通过
this.$api.getPublicKey(({
data
}) => {
this.pbkey = data;
this.doLogin();
})
} else {
return false;
}
});
},
// 登录获取token
doLogin() {
let loginData = {
userName: this.form.userName,
passWord: this.encrypt(this.form.password)
}
this.$api.login(loginData, ({
data
}) => {
localStorage.setItem("emisToken", data);
this.$router.push({
path: '/home'
});
})
},
// 加密
encrypt(pwd) {
const encrypt = new JSEncrypt();
encrypt.setPublicKey(this.pbkey); //设置公钥
return encrypt.encrypt(pwd);
},
// 解密
decrypt(pwd) {
const encrypt = new JSEncrypt();
encrypt.setPrivateKey(privateKey); //设置私钥
return encrypt.decrypt(pwd);
},
// 记住密码
remember(data) {
this.checked = data;
if (this.checked) {
localStorage.setItem("emisLoginInfo", JSON.stringify(this.form))
} else {
localStorage.removeItem("emisLoginInfo")
}
},
},
};
</script>
<style scoped lang="scss">
@import "index.scss";
</style>
样式index.scss
.loginbody {
width: 100%;
height: 100%;
min-width: 1000px;
background: url("~@/assets/images/login/bg.png") no-repeat center/cover;
overflow: auto;
background-repeat: no-repeat;
position: fixed;
line-height: 100%;
padding-top: 300px;
box-sizing: border-box;
.logintext {
margin-bottom: 20px;
line-height: 50px;
text-align: center;
font-size: 60px;
font-weight: bolder;
color: white;
text-shadow: 2px 2px 4px #000;
}
.logindata {
width: 400px;
height: 300px;
transform: translate(-50%);
margin-left: 50%;
}
.tool {
color: #606266;
}
.butt {
text-align: center;
margin: auto;
}
}
背景图:
实现页面:
参考文章:vue+element ui实现好看的登录界面