使用‘js-cookie‘和 ‘crypto-js‘实现登录页面记住密码功能

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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值