1.首先安装 js-cookie、jsencrypt
npm i js-cookie // 使用Cookie来实现记住密码功能
npm i jsencrypt //使用jsencrypt进行加密解密
2.完整代码
注:在此我使用了ant-design-vue组件库 若使用源码请自行配置ant-design-vue
<template><h2 :style="{marginLeft:'45%'}">记住密码demo</h2><a-form:model="formState"name="basic":label-col="{ span: 6 }":wrapper-col="{ span: 12 }"autocomplete="off"@finish="onFinish"@finishFailed="onFinishFailed"><a-form-item label="用户名" name="username"><a-input v-model:value="formState.username" /></a-form-item><a-form-item label="密码" name="password"><a-input-password v-model:value="displayPassword" /></a-form-item><a-form-item name="remember" :wrapper-col="{ offset: 6, span: 12 }"><a-checkbox v-model:checked="formState.remember">记住我</a-checkbox></a-form-item><a-form-item :wrapper-col="{ offset: 6, span: 12 }"><a-button type="primary" html-type="submit">登录</a-button></a-form-item></a-form>
</template><script setup>
import { reactive,computed, onMounted } from "vue";
import Cookies from "js-cookie";
import JSEncrypt from "jsencrypt/bin/jsencrypt.min";const formState = reactive({username: Cookies.get("username") ? Cookies.get("username") : "",password: "",remember: false,
});const displayPassword = computed({get: () => {// 在这里解密密码,仅当有加密的密码存储时才执行解密if (Cookies.get("username")) {return decrypt(Cookies.get("password"));}return ""; // 如果没有加密密码,则返回空字符串},set: (val) => (formState.password = val),
});const publicKey = ''; //公钥
const privateKey = ''; //私钥const onFinish = (values) => {if (formState.remember) {Cookies.set("username", formState.username, { expires: 7 }); //设置有效期为7天Cookies.set("password", encrypt(formState.password), { expires: 7 }); //对密码进行加密} else {Cookies.remove("username");Cookies.remove("password");}
};// 加密const encrypt = (val) => {const encryptor = new JSEncrypt();encryptor.setPublicKey(publicKey); // 设置公钥return encryptor.encrypt(val); // 对数据进行加密
};// 解密
const decrypt = (val) => {const encryptor = new JSEncrypt();encryptor.setPrivateKey(privateKey); // 设置私钥return encryptor.decrypt(val); // 对数据进行解密
};</script>