export type State = { pendingAgreements: boolean, isLogin: boolean, userInfo: UTSJSONObject } // 实例化为state export const state = reactive({ pendingAgreements: false, userInfo: { "_id": null, "avatar_file": null, "nickname": null, "mobile": null, } as UTSJSONObject, isLogin: false } as State) function initState() { try { let userInfo = uni.getStorageSync('uni-id-pages-x-userInfo') console.log('init userInfo',userInfo); // #ifdef APP-IOS userInfo = new UTSJSONObject(userInfo) // #endif if (userInfo instanceof UTSJSONObject) { state.userInfo = userInfo as UTSJSONObject // console.log('init userInfo',userInfo); } } catch (e) { console.error('init userInfo error', e); } state.isLogin = uniCloud.getCurrentUserInfo().tokenExpired > Date.now() }; initState() type Mutations = { updateUserInfo(param: null | UTSJSONObject): void } export const mutations = { updateUserInfo: function (param: null | UTSJSONObject) { //console.log('updateUserInfo', param); // param为 null 时从云端获取数据更新,为UTSJSONObject时直接根据传入的值来更新 function afterUpdateUserInfo() { // console.log('afterUpdateUserInfo', state.userInfo); uni.setStorageSync('uni-id-pages-x-userInfo', state.userInfo) } const db = uniCloud.databaseForJQL() const usersCollection = db.collection('uni-id-users') const user_id = uniCloud.getCurrentUserInfo().uid console.log('user_id', user_id); if(user_id == null){ return } if (param == null) { usersCollection .doc(user_id) .field('_id,username,nickname,avatar_file,mobile') .get() .then(res => { const uniIdCo = uniCloud.importObject('uni-id-co', { customUI: true }) uniIdCo .getRealNameInfo() .then((realNameInfo) => { state.userInfo = Object.assign(res.data[0], { realNameInfo }) afterUpdateUserInfo() }) }) .catch((err: any | null) => { const error = err as UniCloudError console.error(error.errMsg, '错误') }) } else { param.toMap().forEach((value, key) => { state.userInfo.set(key, value) }) usersCollection .doc(user_id) .update(param) afterUpdateUserInfo() } } } as Mutations;