1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- // app.js
- App({
- globalData: {
- userInfo: null,
- theme: {
- bgColor: '#F8F8F8', // 默认背景颜色
- textColor: '#333',
- primaryColor: '#E7624F',
- secondaryTextColor: '#222222'
- },
- logs: [] // 专注记录
- },
- onLaunch: function() {
- // 初始化事件总线
- this.eventBus = {
- events: {},
- on: function(eventName, callback) {
- if (!this.events[eventName]) {
- this.events[eventName] = [];
- }
- this.events[eventName].push(callback);
- },
- off: function(eventName, callback) {
- if (this.events[eventName]) {
- this.events[eventName] = this.events[eventName].filter(
- cb => cb !== callback
- );
- }
- },
- emit: function(eventName, data) {
- if (this.events[eventName]) {
- this.events[eventName].forEach(callback => {
- callback(data);
- });
- }
- }
- };
- // 登录
- wx.login({
- success: res => {
- // 发送 res.code 到后台换取 openId, sessionKey, unionId
- // 建议在获取到用户授权后再调用此接口
- }
- });
- // 尝试从缓存获取用户信息
- try {
- const userInfo = wx.getStorageSync('userInfo');
- if (userInfo) {
- this.globalData.userInfo = userInfo;
- this.eventBus.emit('userInfoChange', userInfo); // 通知所有监听者用户信息已更新
- }
- } catch (e) {
- console.error('获取用户信息缓存失败', e);
- }
- // 获取用户信息
- wx.getSetting({
- success: res => {
- if (res.authSetting['scope.userInfo']) {
- // 已经授权,可以直接调用 getUserProfile 获取头像昵称
- wx.getUserProfile({
- desc: '用于完善用户资料',
- success: res => {
- this.updateUserInfo(res.userInfo);
- // 可以在这里将用户信息发送到后端保存
- }
- });
- }
- }
- });
- },
- // 更新用户信息并存储到本地缓存
- updateUserInfo: function(userInfo) {
- this.globalData.userInfo = userInfo;
- try {
- wx.setStorageSync('userInfo', userInfo);
- this.eventBus.emit('userInfoChange', userInfo); // 通知所有监听者用户信息已更新
- } catch (e) {
- console.error('存储用户信息失败', e);
- }
- }
- });
|