-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
104 lines (91 loc) · 2.3 KB
/
Copy pathapp.js
File metadata and controls
104 lines (91 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
App({
globalData: {
userInfo: null,
systemInfo: null,
cartCount: 0,
isLogin: false
},
onLaunch() {
// 初始化云开发
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
wx.cloud.init({
env: 'your-env-id',
traceUser: true
})
}
// 获取系统信息
this.getSystemInfo()
// 检查登录状态
this.checkLoginStatus()
// 初始化购物车数据
this.initCartData()
console.log('富硒电商小程序启动成功')
},
onShow() {
// 更新购物车数量
this.updateCartCount()
},
// 获取系统信息
getSystemInfo() {
wx.getSystemInfo({
success: (res) => {
this.globalData.systemInfo = res
}
})
},
// 检查登录状态
checkLoginStatus() {
const token = wx.getStorageSync('token')
const userInfo = wx.getStorageSync('userInfo')
if (token && userInfo) {
this.globalData.isLogin = true
this.globalData.userInfo = userInfo
}
},
// 初始化购物车数据
initCartData() {
const cart = wx.getStorageSync('cart') || []
this.globalData.cartCount = cart.reduce((sum, item) => sum + item.count, 0)
},
// 更新购物车数量
updateCartCount() {
const cart = wx.getStorageSync('cart') || []
const count = cart.reduce((sum, item) => sum + item.count, 0)
this.globalData.cartCount = count
// 更新 tabBar 徽章
if (count > 0) {
wx.setTabBarBadge({
index: 2,
text: String(count > 99 ? '99+' : count)
})
} else {
wx.removeTabBarBadge({ index: 2 })
}
},
// 全局登录方法
login() {
return new Promise((resolve, reject) => {
wx.getUserProfile({
desc: '用于完善用户资料',
success: (res) => {
const userInfo = res.userInfo
this.globalData.userInfo = userInfo
this.globalData.isLogin = true
wx.setStorageSync('userInfo', userInfo)
wx.setStorageSync('token', 'mock_token_' + Date.now())
resolve(userInfo)
},
fail: reject
})
})
},
// 全局退出登录
logout() {
this.globalData.userInfo = null
this.globalData.isLogin = false
wx.removeStorageSync('userInfo')
wx.removeStorageSync('token')
}
})