liufumingren 8f1a8b7ddb feat(miniprogram): 新增 uni-app + Vue3 + TS 微信小程序
- 登录:微信一键登录(code2Session)+ 账号登录双 tab;个人中心为整页登录,其它页走抽屉
- 协议:登录前必须阅读并同意,版本号随登录上报落库
- 不强制登录:启动不弹窗,点功能或遇到 401 才提示(符合小程序审核)
- 页面:首页统计 / 扫码记录 / 个人中心;H5 预览端口 7304

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 00:47:16 +08:00

63 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ref } from 'vue';
import { setStoredSubjectId } from '@/composables/subjectStorage';
import type { CurrentUser } from '@/api/types';
/** 令牌与当前用户的本地存放(接口用 header 令牌,不依赖 cookie/session) */
const TOKEN_KEY = 'packs_token';
const USER_KEY = 'packs_user';
/** 当前用户(响应式,个人中心用) */
export const currentUser = ref<CurrentUser | null>(readUser());
/** 登录状态版本号:登录 / 退出 / 令牌失效时 +1,页面 watch 它来刷新数据 */
export const authVersion = ref(0);
function readUser(): CurrentUser | null {
try {
const raw = uni.getStorageSync(USER_KEY);
if (!raw) return null;
return typeof raw === 'string' ? (JSON.parse(raw) as CurrentUser) : (raw as CurrentUser);
} catch {
return null;
}
}
export function getToken(): string {
try {
return String(uni.getStorageSync(TOKEN_KEY) || '');
} catch {
return '';
}
}
export function setSession(token: string, user: CurrentUser): void {
uni.setStorageSync(TOKEN_KEY, token);
uni.setStorageSync(USER_KEY, user);
currentUser.value = user;
authVersion.value += 1;
}
export function setUser(user: CurrentUser): void {
uni.setStorageSync(USER_KEY, user);
currentUser.value = user;
}
export function clearSession(): void {
uni.removeStorageSync(TOKEN_KEY);
uni.removeStorageSync(USER_KEY);
// 换账号后不能带着上一个账号的主体 id
setStoredSubjectId(null);
currentUser.value = null;
authVersion.value += 1;
}
export function isLoggedIn(): boolean {
return Boolean(getToken());
}
/** 显示名 */
export function displayName(user: CurrentUser | null = currentUser.value): string {
if (!user) return '';
return user.nickname || user.username || `#${user.id}`;
}