import { getStorage, TOKEN_KEY } from './storage.js' // 需要登录才能访问的页面路径列表 const AUTH_PAGES = [ '/pages/mine/mine', '/pages/points/points', '/pages/coupons/coupons', '/pages/about/about' ] /** * 检查页面是否需要登录 * @param {string} pagePath - 页面路径 * @returns {boolean} */ export function isAuthRequired(pagePath) { // 统一格式:确保以 / 开头 const path = pagePath.startsWith('/') ? pagePath : `/${pagePath}` return AUTH_PAGES.some(p => path.startsWith(p)) } /** * 检查用户是否已登录 * @returns {boolean} */ export function isAuthenticated() { return !!getStorage(TOKEN_KEY) } /** * 路由守卫:检查目标页面是否需要登录,未登录则跳转登录页 * @param {string} pagePath - 目标页面路径 * @returns {boolean} true表示允许访问,false表示已拦截跳转登录页 */ export function checkAuth(pagePath) { if (isAuthRequired(pagePath) && !isAuthenticated()) { uni.navigateTo({ url: '/pages/login/login' }) return false } return true } /** * 初始化应用状态(在App.vue onLaunch中调用) * - 初始化语言设置 * - 如果已登录则获取用户信息 */ export async function initAppState() { const { useAppStore } = await import('../stores/app.js') const { useUserStore } = await import('../stores/user.js') const appStore = useAppStore() const userStore = useUserStore() // 初始化语言 appStore.initLocale() // 如果有Token,尝试获取用户信息 if (userStore.isLoggedIn) { try { await userStore.fetchUserInfo() } catch (e) { // 获取失败(如Token过期)由请求拦截器处理401 console.warn('初始化用户信息失败:', e.message) } } }