index.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // 工具函数集合
  2. /**
  3. * 显示加载提示
  4. * @param {string} title - 提示文字
  5. */
  6. export const showLoading = (title = '加载中') => {
  7. uni.showLoading({
  8. title,
  9. mask: true
  10. })
  11. }
  12. /**
  13. * 隐藏加载提示
  14. */
  15. export const hideLoading = () => {
  16. uni.hideLoading()
  17. }
  18. /**
  19. * 显示Toast提示
  20. * @param {string} title - 提示文字
  21. * @param {string} icon - 图标类型 success | error | loading | none
  22. * @param {number} duration - 显示时长
  23. */
  24. export const showToast = (title, icon = 'none', duration = 2000) => {
  25. uni.showToast({
  26. title,
  27. icon,
  28. duration
  29. })
  30. }
  31. /**
  32. * 缓存工具类
  33. */
  34. export const storage = {
  35. /**
  36. * 设置缓存
  37. * @param {string} key - 缓存键
  38. * @param {any} value - 缓存值
  39. */
  40. set(key, value) {
  41. if (typeof value === 'object') {
  42. value = JSON.stringify(value)
  43. }
  44. uni.setStorageSync(key, value)
  45. },
  46. /**
  47. * 获取缓存
  48. * @param {string} key - 缓存键
  49. * @returns {any} 缓存值
  50. */
  51. get(key) {
  52. const value = uni.getStorageSync(key)
  53. try {
  54. return JSON.parse(value)
  55. } catch (e) {
  56. return value
  57. }
  58. },
  59. /**
  60. * 删除缓存
  61. * @param {string} key - 缓存键
  62. */
  63. remove(key) {
  64. uni.removeStorageSync(key)
  65. },
  66. /**
  67. * 清空缓存
  68. */
  69. clear() {
  70. uni.clearStorageSync()
  71. }
  72. }
  73. /**
  74. * 时间格式化
  75. * @param {number|string} time - 时间戳或日期字符串
  76. * @param {string} format - 格式化模板
  77. * @returns {string} 格式化后的时间字符串
  78. */
  79. export const formatTime = (time, format = 'YYYY-MM-DD HH:mm:ss') => {
  80. const date = new Date(time)
  81. const year = date.getFullYear()
  82. const month = String(date.getMonth() + 1).padStart(2, '0')
  83. const day = String(date.getDate()).padStart(2, '0')
  84. const hour = String(date.getHours()).padStart(2, '0')
  85. const minute = String(date.getMinutes()).padStart(2, '0')
  86. const second = String(date.getSeconds()).padStart(2, '0')
  87. return format
  88. .replace('YYYY', year)
  89. .replace('MM', month)
  90. .replace('DD', day)
  91. .replace('HH', hour)
  92. .replace('mm', minute)
  93. .replace('ss', second)
  94. }
  95. /**
  96. * 金额格式化(支持元或分,保留两位小数)
  97. * @param {number|string} amount - 金额(元或分)
  98. * @param {boolean} isCent - 是否为分单位(默认为true,因为项目中金额单位均为分)
  99. * @returns {string} 格式化后的金额(元)
  100. */
  101. export const formatAmount = (amount, isCent = true) => {
  102. if (amount === null || amount === undefined || isNaN(amount)) {
  103. return '0.00'
  104. }
  105. // 将金额转换为数字
  106. const numAmount = parseFloat(amount)
  107. // 根据单位转换为元
  108. const yuan = isCent ? numAmount / 100 : numAmount
  109. // 保留两位小数
  110. return yuan.toFixed(2)
  111. }
  112. /**
  113. * 获取请求头
  114. * @returns {Object} 请求头
  115. */
  116. export const getHeaders = () => {
  117. const token = storage.get('token')
  118. const headers = {
  119. 'Content-Type': 'application/json'
  120. }
  121. if (token) {
  122. headers['accessToken'] = token
  123. }
  124. return headers
  125. }
  126. /**
  127. * 网络请求工具
  128. * @param {Object} config - 请求配置
  129. * @returns {Promise} 请求结果
  130. */
  131. export const request = (config) => {
  132. const {
  133. url,
  134. method = 'GET',
  135. data = {},
  136. showLoad = true
  137. } = config
  138. if (showLoad) {
  139. showLoading()
  140. }
  141. // 根据admin-web配置,基础API地址为后台服务地址
  142. // 请根据实际部署情况修改此地址
  143. const baseApi = 'https://dev-wash-cloud.kuaiyuman.cn/admin' // admin-web的后台服务地址
  144. const fullUrl = `${baseApi}${url}`
  145. console.log(`发起${method}请求:`, fullUrl)
  146. // 对于GET请求,如果data不为空,将其作为查询参数
  147. const requestConfig = {
  148. url: fullUrl,
  149. method,
  150. header: getHeaders()
  151. }
  152. // GET请求使用查询参数,POST/PUT/DELETE使用请求体
  153. if (method === 'GET' && Object.keys(data).length > 0) {
  154. requestConfig.data = data
  155. } else if (method !== 'GET') {
  156. requestConfig.data = data
  157. }
  158. return new Promise((resolve, reject) => {
  159. uni.request({
  160. ...requestConfig,
  161. success: (res) => {
  162. if (showLoad) {
  163. hideLoading()
  164. }
  165. const { statusCode, data } = res
  166. console.log(`请求响应 [${statusCode}]:`, fullUrl, data)
  167. if (statusCode === 200) {
  168. // 登录成功后保存token
  169. if (url === '/admin-user/login' && data.code === 200) {
  170. storage.set('token', data.data.accessToken)
  171. }
  172. if (data.code === 200) {
  173. resolve(data)
  174. } else {
  175. showToast(data.msg || '请求失败')
  176. reject(data)
  177. }
  178. } else if (statusCode === 401) {
  179. showToast('登录已过期,请重新登录')
  180. storage.remove('token')
  181. uni.navigateTo({
  182. url: '/pages/login/login'
  183. })
  184. reject(data)
  185. } else {
  186. showToast(`请求失败(${statusCode})`)
  187. reject(data)
  188. }
  189. },
  190. fail: (err) => {
  191. if (showLoad) {
  192. hideLoading()
  193. }
  194. console.error('网络请求失败:', fullUrl, err)
  195. showToast('网络请求失败,请检查网络连接')
  196. reject(err)
  197. }
  198. })
  199. })
  200. }
  201. /**
  202. * GET请求
  203. * @param {string} url - 请求地址
  204. * @param {Object} data - 请求参数
  205. * @param {boolean} showLoad - 是否显示加载提示
  206. * @returns {Promise} 请求结果
  207. */
  208. export const get = (url, data = {}, showLoad = true) => {
  209. return request({
  210. url,
  211. method: 'GET',
  212. data,
  213. showLoad
  214. })
  215. }
  216. /**
  217. * POST请求
  218. * @param {string} url - 请求地址
  219. * @param {Object} data - 请求参数
  220. * @param {boolean} showLoad - 是否显示加载提示
  221. * @returns {Promise} 请求结果
  222. */
  223. export const post = (url, data = {}, showLoad = true) => {
  224. return request({
  225. url,
  226. method: 'POST',
  227. data,
  228. showLoad
  229. })
  230. }