1安装组件
npm i js-cookie
npm i crypto-js
2 使用
(1)写加密和解密函数
import Cookies from 'js-cookie'
import CryptoJS from 'crypto-js'
// 密钥,实际应用中应该保密且随机生成
const secretKey = 'sc202407311534'
// 加密函数
function encryptPassword(password: string | CryptoJS.lib.WordArray) {
return CryptoJS.AES.encrypt(password, secretKey).toString()
}
// 解密函数
function decryptPassword(encryptedPassword: string | CryptoJS.lib.CipherParams) {
const bytes = CryptoJS.AES.decrypt(encryptedPassword, secretKey)
return bytes.toString(CryptoJS.enc.Utf8)
}
(2) 登录
//表单数据
const form = reactive({
name: '',
password: ''
})
//记住密码
const rememberMe = ref(false)
//登录按钮
const submit = (data: { name: string; password: string }) => {
// 1 格式验证 省略
// 2 向后端发请求 验证用户密码
API.login(form)
.then((res: any) => {
if (rememberMe.value == true) {//记住密码为true
// 3 存储
Cookies.set('user_name', form.name, { expires: 1 }) // 假设过期时间为1天
Cookies.set('user_password', encryptPassword(form.password), { expires: 1 })
} else {
// 清除密码
Cookies.remove('user_password')
}
router.push('/home') //通过之后跳转页面
})
.catch((err: any) => {
//用户密码错误逻辑
console.log(err)
})
}
(3) 获取账号密码
//自动填充密码
const autoFillLoginForm = () => {
// 1 cookie中读取 账户密码
const user_name = Cookies.get('user_name')
const encryptedPassword = Cookies.get('user_password')
if (encryptedPassword) {
// 2 解密
const user_password = decryptPassword(encryptedPassword)
form.name = user_name
form.password = user_password
}
rememberMe.value = true
}