第一步:插件安装 
js-base64 用来对用户名和密码加密

npm install js-base64


js-cookie 用来存储用户名和密码

npm install js-cookie

第二步:存储逻辑
点击登录,在登录前对用户的用户名和密码进行加密,然后保存到cookie

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      console.log('error submit!', fields)
      return
    }
    loading.value = true

    // 转码
    const { username, password, verifyCode } = form
    const params = {
      username: encode(username),
      password: encode(password),
      verifyCode
    }

    // 检测是否需要记住密码
    if (remember.value) {
      const { username, password } = params
      const localForm = {
        username,
        password
      }
      jsCookie.set(LOCAL_KEY, JSON.stringify(localForm))
    } else {
      jsCookie.remove(LOCAL_KEY)
    }

    store.dispatch('user/login', form).then((res) => {
      const redirectPage: any = route.query.redirect || '/'
      router.replace(redirectPage)
    }).finally(() => {
      loading.value = false
    })
  })
}


 

第三步:因为保存了密码之后我们还需要在页面进入的时候进行调取用户名和密码,所以要做一个解析的方法

const queryLocalForm = () => {
  const localForm = jsCookie.get(LOCAL_KEY)
  if (localForm) {
    remember.value = true
    try {
      const { username, password } = JSON.parse(localForm)
      form.username = decode(username)
      form.password = decode(password)
    } catch (error) {
      console.error('本地数据解析失败~', error)
    }
  } else {
    remember.value = false
  }
}

Logo

前往低代码交流专区

更多推荐