pet/App.vue

131 lines
3.3 KiB
Vue
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.

<script>
import { wxLogin } from '@/http/api/auth.js'
export default {
onLaunch: function() {
console.log('App Launch')
this.initApp()
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
},
methods: {
// 应用初始化
async initApp() {
console.log('应用初始化开始')
await this.checkAutoLogin()
},
// 等待HTTP配置初始化
async waitForHttpInit() {
// 等待uni.$u.http可用
let retryCount = 0
const maxRetries = 10
while (!uni.$u || !uni.$u.http) {
if (retryCount >= maxRetries) {
throw new Error('HTTP配置初始化超时')
}
await new Promise(resolve => setTimeout(resolve, 100))
retryCount++
}
console.log('HTTP配置初始化完成')
},
// 检查自动登录
async checkAutoLogin() {
try {
// 检查本地是否有有效token
const token = uni.getStorageSync('token')
if (token) {
// 已有token直接跳过WebSocket初始化
console.log('已有token跳过WebSocket初始化')
return
}
// 等待HTTP配置初始化完成
await this.waitForHttpInit()
// 获取微信登录code
const loginRes = await new Promise((resolve, reject) => {
uni.login({
success: resolve,
fail: (error) => {
console.warn('微信登录失败:', error)
// 不reject而是resolve一个空对象避免阻止应用启动
resolve({ code: null, error })
}
})
})
if (loginRes.code) {
// 调用后端登录接口
const result = await uni.$u.http.post('/wechat/user/mini/login', {
code: loginRes.code
}, {
custom: {
loading: false,
toast: false,
auth: false
}
})
if (result && result.token) {
// 用户已授权过手机号,保存登录信息
await this.saveLoginData(result)
} else {
// 用户未授权手机号保存微信登录code供后续使用
this.saveWxCode(loginRes.code)
}
}
} catch (error) {
// 静默处理错误,不影响应用正常启动
console.error('自动登录失败:', error)
}
},
// 保存登录数据
async saveLoginData(result) {
uni.setStorageSync('token', result.token)
if (result.refreshToken) {
uni.setStorageSync('refreshToken', result.refreshToken)
}
if (result.userInfo) {
uni.setStorageSync('wxUserInfo', result.userInfo)
uni.setStorageSync('userInfo', result.userInfo)
}
// 设置登录状态
const loginStep = result.userInfo && result.userInfo.profileCompleted
? 'profile_completed'
: 'phone_authed'
uni.setStorageSync('loginStep', loginStep)
// 跳过WebSocket初始化
console.log('登录成功跳过WebSocket初始化')
},
// 保存微信code
saveWxCode(code) {
uni.setStorageSync('wxLoginCode', code)
uni.setStorageSync('loginDate', new Date().toISOString())
uni.setStorageSync('loginStep', 'wx_logged')
},
// WebSocket功能已移除保留方法避免调用错误
async initWebSocketConnection(token) {
console.log('WebSocket功能已移除使用HTTP API替代')
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uview-next/index.scss";
</style>