app.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // app.js
  2. App({
  3. globalData: {
  4. userInfo: null,
  5. theme: {
  6. bgColor: '#F8F8F8', // 默认背景颜色
  7. textColor: '#333',
  8. primaryColor: '#E7624F',
  9. secondaryTextColor: '#222222'
  10. },
  11. logs: [] // 专注记录
  12. },
  13. onLaunch: function() {
  14. // 初始化事件总线
  15. this.eventBus = {
  16. events: {},
  17. on: function(eventName, callback) {
  18. if (!this.events[eventName]) {
  19. this.events[eventName] = [];
  20. }
  21. this.events[eventName].push(callback);
  22. },
  23. off: function(eventName, callback) {
  24. if (this.events[eventName]) {
  25. this.events[eventName] = this.events[eventName].filter(
  26. cb => cb !== callback
  27. );
  28. }
  29. },
  30. emit: function(eventName, data) {
  31. if (this.events[eventName]) {
  32. this.events[eventName].forEach(callback => {
  33. callback(data);
  34. });
  35. }
  36. }
  37. };
  38. // 登录
  39. wx.login({
  40. success: res => {
  41. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  42. // 建议在获取到用户授权后再调用此接口
  43. }
  44. });
  45. // 尝试从缓存获取用户信息
  46. try {
  47. const userInfo = wx.getStorageSync('userInfo');
  48. if (userInfo) {
  49. this.globalData.userInfo = userInfo;
  50. this.eventBus.emit('userInfoChange', userInfo); // 通知所有监听者用户信息已更新
  51. }
  52. } catch (e) {
  53. console.error('获取用户信息缓存失败', e);
  54. }
  55. // 获取用户信息
  56. wx.getSetting({
  57. success: res => {
  58. if (res.authSetting['scope.userInfo']) {
  59. // 已经授权,可以直接调用 getUserProfile 获取头像昵称
  60. wx.getUserProfile({
  61. desc: '用于完善用户资料',
  62. success: res => {
  63. this.updateUserInfo(res.userInfo);
  64. // 可以在这里将用户信息发送到后端保存
  65. }
  66. });
  67. }
  68. }
  69. });
  70. },
  71. // 更新用户信息并存储到本地缓存
  72. updateUserInfo: function(userInfo) {
  73. this.globalData.userInfo = userInfo;
  74. try {
  75. wx.setStorageSync('userInfo', userInfo);
  76. this.eventBus.emit('userInfoChange', userInfo); // 通知所有监听者用户信息已更新
  77. } catch (e) {
  78. console.error('存储用户信息失败', e);
  79. }
  80. }
  81. });