一、效果:
二、实现:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
<script>
export default {
name: 'Login',
data() {
return {
formData: {},
};
},
created() {
if (localStorage.getItem("BASIC_LOGIN")) {
this.formData = JSON.parse(localStorage.getItem("BASIC_LOGIN"))
}
},
methods: {
/* 登录按钮 */
handleSubmit() {
const that = this;
that.$refs.elForm.validate(valid => {
if (valid) {
that.loading = true;
let param = { ...this.formData }
if (localStorage.getItem("BASIC_LOGIN")) {
param.password = this.encryptANDdecrypt(this.formData.password, "decrypt")
}
loginAPI(param).then(res => {
if (res.data && res.data.code == 0) {
if (that.formData.checked == true) {
that.formData.password = that.encryptANDdecrypt(param.password, "encrypt")
localStorage.setItem("BASIC_LOGIN", JSON.stringify(that.formData))
} else {
localStorage.removeItem("BASIC_LOGIN")
}
that.$store.commit('setUser', res.data.data)
that.$router.push({ path: '/Home' }).catch(() => { });
} else {
that.$message.error(res.data.msg);
}
}).finally(() => {
that.loading = false;
})
}
});
},
// 加解密算法
encryptANDdecrypt(data, type) {
const key = '0123456789abcdef' // 密钥, AES-128 需16个字符, AES-256 需要32个字符
const iv = 'abcdef0123456789' // 密钥偏移量,16个字符
if (type == 'encrypt') {// 加密
const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data), CryptoJS.enc.Utf8.parse(key), {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return encrypted.toString()
} else {// 解密
const decrypted = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return CryptoJS.enc.Utf8.stringify(decrypted).toString()
}
},
}
};
</script>