登录时记住密码功能一般可以用sessionStorage,sessionStorage,Cookie实现,以下表格是三者间的差异:
图片来源
此处我使用的是Cookie来实现记住密码功能(js-cookie),使用jsencrypt对密码进行加密解密
npm i js-cookie -s
npm i jsencrypt -s
实现完整代码:
<template>
<el-form
ref="ruleFormRef"
:model="ruleForm"
status-icon
:rules="rules"
label-width="80px"
label-position="left"
class="demo-ruleForm"
>
<el-form-item label="用户名" prop="username">
<el-input v-model="ruleForm.username" />
</el-form-item>
<el-form-item label="密码" prop="pass">
<el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
</el-form-item>
<el-form-item label="" prop="remerber">
<el-checkbox
v-model="ruleForm.remerber"
label="记住密码"
size="large"
style="float: left"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm(ruleFormRef)"
>登录</el-button
>
<el-button @click="resetForm(ruleFormRef)">重置</el-button>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { CommonPicker, type FormInstance, type FormRules } from "element-plus";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "./jsencrypt";
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
username: "",
pass: "",
remerber: false,
});
const rules = {
username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
pass: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
};
const submitForm = (formEl: FormInstance | undefined) => {
if (!formEl) return;
formEl.validate((valid) => {
if (valid) {
if (ruleForm.remerber) {
Cookies.set("username", ruleForm.username, { expires: 30 }); //设置有效期为30天
Cookies.set("password", encrypt(ruleForm.pass), { expires: 30 });
}else{
Cookies.remove('username')
Cookies.remove('password')
}
} else {
return false;
}
});
};
const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return;
formEl.resetFields();
};
const getCookie = () => {
let username = Cookies.get('username')
let pass = Cookies.get('password')
ruleForm.username = username === undefined?ruleForm.username:username
ruleForm.pass = pass === undefined?ruleForm.pass:decrypt(pass)
};
getCookie()
</script>
<style scoped lang="less">
.demo-ruleForm {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 400px;
background-color: antiquewhite;
padding: 40px 20px;
border-radius: 10px;
}
</style>
jsencrypt.ts
:
密钥对生成 http://web.chacuo.net/netrsakeypair
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
const publicKey = ``
const privateKey = ``
// 加密
export function encrypt(txt:string) {
const encryptor = new JSEncrypt()
encryptor.setPublicKey(publicKey) // 设置公钥
return encryptor.encrypt(txt) // 对数据进行加密
}
// 解密
export function decrypt(txt:string) {
const encryptor = new JSEncrypt()
encryptor.setPrivateKey(privateKey) // 设置私钥
return encryptor.decrypt(txt) // 对数据进行解密
}
页面
:
控制台
可看到储存的cookie