loginAccounts.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /** 本地历史账号(登录页「记住密码」与个人中心「切换账号」共用) */
  2. export const LOGIN_ACCOUNTS_KEY = 'login_saved_accounts'
  3. export const LOGIN_PENDING_SWITCH_KEY = 'login_pending_switch'
  4. export function loadSavedAccounts() {
  5. try {
  6. const raw = uni.getStorageSync(LOGIN_ACCOUNTS_KEY)
  7. if (raw == null || raw === '') return []
  8. const arr = typeof raw === 'string' ? JSON.parse(raw) : raw
  9. return Array.isArray(arr) ? arr : []
  10. } catch (e) {
  11. return []
  12. }
  13. }
  14. export function saveAccounts(list) {
  15. try {
  16. uni.setStorageSync(LOGIN_ACCOUNTS_KEY, JSON.stringify(list))
  17. } catch (e) {}
  18. }
  19. /** 历史账号展示:姓名 + 空格 + 手机号(仅存本地) */
  20. export function formatSavedAccountLabel(acc) {
  21. const mobile = String(acc && acc.mobile != null ? acc.mobile : '').trim()
  22. const name = acc && acc.name != null ? String(acc.name).trim() : ''
  23. if (name && mobile) return `${name} ${mobile}`
  24. return mobile || name
  25. }
  26. /**
  27. * 切换账号:清会话后写入待登录信息,登录页 onLoad 消费并自动密码登录
  28. * @param {{ mobile: string, password: string }} account
  29. */
  30. export function setPendingSwitchAccount(account) {
  31. try {
  32. uni.setStorageSync(
  33. LOGIN_PENDING_SWITCH_KEY,
  34. JSON.stringify({
  35. mobile: String(account.mobile || '').trim(),
  36. password: account.password != null ? String(account.password) : ''
  37. })
  38. )
  39. } catch (e) {}
  40. }
  41. /** 读取并清除待切换账号;无效则返回 null */
  42. export function consumePendingSwitchAccount() {
  43. let raw
  44. try {
  45. raw = uni.getStorageSync(LOGIN_PENDING_SWITCH_KEY)
  46. } catch (e) {
  47. return null
  48. }
  49. try {
  50. uni.removeStorageSync(LOGIN_PENDING_SWITCH_KEY)
  51. } catch (e) {}
  52. if (raw == null || raw === '') return null
  53. try {
  54. const o = typeof raw === 'string' ? JSON.parse(raw) : raw
  55. const mobile = o && String(o.mobile || '').trim()
  56. const password = o && o.password != null ? String(o.password) : ''
  57. if (!mobile || !password) return null
  58. return { mobile, password }
  59. } catch (e) {
  60. return null
  61. }
  62. }