增加线上配置分享功能+用户后台登录,不影响首页渲染
This commit is contained in:
@@ -4,27 +4,48 @@ const { request } = require('./utils/api')
|
||||
|
||||
App({
|
||||
onLaunch() {
|
||||
// 自动静默登录:wx.login 获取 code,再请求后端接口换取 openid
|
||||
// 优先从本地缓存恢复登录态,避免阻塞页面
|
||||
const cached = wx.getStorageSync('userInfo')
|
||||
if (cached && cached.openid) {
|
||||
this.globalData.userInfo = cached
|
||||
this.globalData.isLoggedIn = true
|
||||
}
|
||||
// 静默登录获取最新 session,不阻塞页面
|
||||
this.silentLogin()
|
||||
},
|
||||
|
||||
silentLogin() {
|
||||
wx.login({
|
||||
success: (loginRes) => {
|
||||
if (loginRes.code) {
|
||||
this.loginWithCode(loginRes.code)
|
||||
} else {
|
||||
console.error('wx.login 失败', loginRes.errMsg)
|
||||
this._loginPromise = new Promise((resolve) => {
|
||||
this._loginResolve = resolve
|
||||
wx.login({
|
||||
success: (loginRes) => {
|
||||
if (loginRes.code) {
|
||||
this.loginWithCode(loginRes.code)
|
||||
} else {
|
||||
console.error('wx.login 失败', loginRes.errMsg)
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('wx.login 调用失败', err)
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('wx.login 调用失败', err)
|
||||
this.handleLoginFail()
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 返回登录完成的 Promise,供页面 await 使用
|
||||
* @param {boolean} useCache - 是否在已有缓存时立即 resolve
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
waitLogin(useCache = false) {
|
||||
if (useCache && this.globalData.isLoggedIn) {
|
||||
return Promise.resolve(this.globalData.userInfo)
|
||||
}
|
||||
return this._loginPromise || Promise.resolve(this.globalData.userInfo || null)
|
||||
},
|
||||
|
||||
async loginWithCode(code) {
|
||||
try {
|
||||
const data = await request({
|
||||
@@ -39,22 +60,25 @@ App({
|
||||
}
|
||||
this.globalData.userInfo = userInfo
|
||||
this.globalData.isLoggedIn = true
|
||||
this.globalData.loginFailed = false
|
||||
wx.setStorageSync('userInfo', userInfo)
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(userInfo)
|
||||
}
|
||||
if (this._loginResolve) this._loginResolve(userInfo)
|
||||
} catch (err) {
|
||||
console.error('后端登录失败', err)
|
||||
this.handleLoginFail()
|
||||
// 如果有缓存登录态,登录失败不立即清除,让页面继续使用缓存
|
||||
if (!this.globalData.isLoggedIn) {
|
||||
this.handleLoginFail()
|
||||
} else {
|
||||
this.globalData.loginFailed = true
|
||||
if (this._loginResolve) this._loginResolve(this.globalData.userInfo)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
handleLoginFail() {
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
if (this._loginResolve) this._loginResolve(null)
|
||||
},
|
||||
|
||||
globalData: {
|
||||
|
||||
Reference in New Issue
Block a user