Files
worldcup-mini/src/stores/user.js
T
hello-dd-code baeb5bd179 feat: 初始化世界杯观赛助手小程序
- uni-app (Vue3) + Vite 框架
- 7个页面:首页、赛程、比赛详情、球队、球队详情、球员、个人中心
- API 接口配置 (开发/生产环境)
- 状态管理 (Pinia)
2026-04-28 15:55:35 +08:00

66 lines
1.7 KiB
JavaScript

import { defineStore } from 'pinia'
import { MINI_PROGRAM_ID } from '@/config'
import { devLogin, login } from '@/api/worldcup'
import { storage, TOKEN_KEY, USER_KEY } from '@/utils/storage'
export const useUserStore = defineStore('user', {
state: () => ({
token: storage.get(TOKEN_KEY) || '',
user: storage.get(USER_KEY) || null,
loginPromise: null
}),
actions: {
async silentLogin(force = false) {
if (this.token && !force) return this.token
if (this.loginPromise) return this.loginPromise
this.loginPromise = new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.login({
provider: 'weixin',
success: async (res) => {
try {
const payload = await login({
mini_program_id: MINI_PROGRAM_ID,
code: res.code
})
this.saveLogin(payload.data)
resolve(this.token)
} catch (e) {
reject(e)
} finally {
this.loginPromise = null
}
},
fail: (err) => {
this.loginPromise = null
reject(err)
}
})
// #endif
// #ifndef MP-WEIXIN
devLogin({ mini_program_id: MINI_PROGRAM_ID })
.then((payload) => {
this.saveLogin(payload.data)
resolve(this.token)
})
.catch(reject)
.finally(() => {
this.loginPromise = null
})
// #endif
})
return this.loginPromise
},
saveLogin(data) {
this.token = data?.token || ''
this.user = data?.user || null
storage.set(TOKEN_KEY, this.token)
storage.set(USER_KEY, this.user)
}
}
})