utils.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. const app_info = require("@/static/appInfo.js");
  2. const api_host = app_info.api_host
  3. const version = app_info.version
  4. const api_prefix = api_host + '/addons/exam/'
  5. //工具类
  6. module.exports = {
  7. timestamp() {
  8. return parseInt(new Date().getTime() / 1000);
  9. },
  10. cons_log(...params) {
  11. for (let p of params) {
  12. console.log(p);
  13. }
  14. },
  15. cons_log_json(...params) {
  16. for (let p of params) {
  17. console.log(JSON.stringify(p));
  18. }
  19. },
  20. goto(url) {
  21. uni.navigateTo({
  22. url: url
  23. });
  24. },
  25. goreto(url) {
  26. uni.redirectTo({
  27. url: url
  28. });
  29. },
  30. gotore(url) {
  31. uni.reLaunch({
  32. url: url
  33. });
  34. },
  35. goback(delta = 1) {
  36. uni.navigateBack({
  37. delta: delta
  38. });
  39. },
  40. toast(msg, icon = 'none', duration = 2000, mask = false, image = '') {
  41. uni.showToast({
  42. title: msg,
  43. icon: icon,
  44. duration: duration,
  45. mask: mask,
  46. image: image
  47. })
  48. },
  49. alert(content, callBack) {
  50. uni.hideLoading();
  51. uni.showModal({
  52. content: content,
  53. showCancel: false,
  54. success: function() {
  55. if (callBack != undefined) {
  56. callBack();
  57. }
  58. }
  59. })
  60. },
  61. getData(key, is_clear = false) {
  62. var value = uni.getStorageSync(key);
  63. if (is_clear) {
  64. uni.setStorageSync(key, '');
  65. }
  66. // console.log('get cache', key, value)
  67. return value;
  68. },
  69. setData(key, value) {
  70. // console.log('set cache', key, value)
  71. uni.setStorageSync(key, value);
  72. },
  73. array_column(obj, key) {
  74. var objects = [];
  75. for (var i in obj) {
  76. if (!obj.hasOwnProperty(i)) continue;
  77. if (typeof obj[i] == 'object') {
  78. objects = objects.concat(this.array_column(obj[i], key));
  79. } else if (i == key) {
  80. objects.push(obj[i]);
  81. }
  82. }
  83. return objects;
  84. },
  85. shuffle(arr) {
  86. var l = arr.length
  87. var index, temp
  88. while (l > 0) {
  89. index = Math.floor(Math.random() * l)
  90. temp = arr[l - 1]
  91. arr[l - 1] = arr[index]
  92. arr[index] = temp
  93. l--
  94. }
  95. return arr
  96. },
  97. // 秒数转时分秒格式
  98. sec_to_time(s) {
  99. var t;
  100. if (s > -1) {
  101. var hour = Math.floor(s / 3600);
  102. var min = Math.floor(s / 60) % 60;
  103. var sec = s % 60;
  104. if (hour < 10) {
  105. t = '0' + hour + ":";
  106. } else {
  107. t = hour + ":";
  108. }
  109. if (min < 10) {
  110. t += "0";
  111. }
  112. t += min + ":";
  113. if (sec < 10) {
  114. t += "0";
  115. }
  116. t += sec.toFixed(2);
  117. }
  118. return t;
  119. },
  120. login() {
  121. var token = this.getData('token');
  122. var user = this.getData('user');
  123. if (!token || !user) {
  124. const pages = getCurrentPages()
  125. const currentPage = pages[pages.length - 1]
  126. const url = currentPage.route
  127. const options = currentPage.options
  128. let urlWithArgs = `/${url}?`
  129. for (let key in options) {
  130. const value = options[key]
  131. urlWithArgs += `${key}=${value}&`
  132. }
  133. urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  134. uni.setStorageSync('route', urlWithArgs);
  135. console.log('没有缓存数据,需先授权')
  136. uni.redirectTo({
  137. url: "/pages/login/login"
  138. })
  139. return;
  140. }
  141. return true;
  142. },
  143. /**
  144. * rich-text富文本中图片宽度最大100%
  145. * @param {String} html
  146. */
  147. formatRichText(html) {
  148. // 去掉img标签里的style、width、height属性
  149. let content_data= html.replace(/<img[^>]*>/gi, function(match,capture) {
  150. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
  151. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
  152. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
  153. return match
  154. })
  155. // 修改所有style里的width属性为max-width:100%
  156. content_data = content_data.replace(/style="[^"]+"/gi,function(match,capture){
  157. match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
  158. return match
  159. })
  160. // 去掉<br/>标签
  161. content_data = content_data.replace(/<br[^>]*\/>/gi, '')
  162. // img标签添加style属性:max-width:100%;height:auto
  163. content_data = content_data.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0px auto;"')
  164. return content_data
  165. },
  166. /**
  167. * http请求
  168. * @param handler
  169. * @param path
  170. * @param data
  171. * @param method
  172. * @param showLoading
  173. * @returns {Promise<unknown>}
  174. */
  175. http(handler, path, data = {}, method = 'post', showLoading = true) {
  176. let url = api_prefix + path
  177. let timestamp = Date.parse(new Date())
  178. if (typeof(data) == 'object') {
  179. data['timestamp'] = timestamp
  180. }
  181. if (showLoading) {
  182. uni.showLoading({
  183. title: '加载中..',
  184. mask: true
  185. })
  186. }
  187. return new Promise((resolve, reject) => {
  188. uni.request({
  189. url: url,
  190. method: method,
  191. data: data,
  192. header: {
  193. 'content-type': 'application/json',
  194. 'token': this.getData('token'),
  195. 'app-version': version
  196. },
  197. success: (res => {
  198. console.log('http res', res)
  199. if (res.statusCode == 200) {
  200. resolve(res.data)
  201. } else {
  202. console.log('http statusCode', res.statusCode)
  203. uni.showToast({
  204. title: res.data.message,
  205. icon: 'none'
  206. })
  207. // 未登录
  208. if (res.statusCode == 401) {
  209. // console.log('this.$refs', this.$refs)
  210. // this.$refs.login.modal = true
  211. // uni.$emit('uniLogin', handler)
  212. handler.$refs.login.modal = true
  213. // handler.$refs.login.afterMethod = () => {
  214. // this.http(handler, path, data)
  215. // }
  216. }
  217. // reject(res.data);
  218. }
  219. }),
  220. fail: (res => {
  221. console.log(res)
  222. return false;
  223. }),
  224. complete: (res => {
  225. showLoading && uni.hideLoading()
  226. })
  227. })
  228. })
  229. },
  230. /**
  231. * 上传文件
  232. * @returns {Promise<*>}
  233. */
  234. uploadFile(handler, filePath, data = {}, fileType = 'image', showLoading = true) {
  235. if (showLoading) {
  236. uni.showLoading({
  237. title: '加载中..',
  238. mask: true
  239. })
  240. }
  241. return new Promise((resolve, reject) => {
  242. uni.uploadFile({
  243. url: api_prefix + 'common/upload',
  244. header: {
  245. 'token': uni.getStorageSync('token'),
  246. "Content-Type": "multipart/form-data"
  247. },
  248. fileType: fileType,
  249. filePath: filePath,
  250. formData: data,
  251. name: 'file',
  252. success: (res) => {
  253. console.log('upload res', res)
  254. let data = JSON.parse(res.data)
  255. if (res.statusCode == 200) {
  256. resolve(data)
  257. } else {
  258. console.log('upload statusCode', res.statusCode)
  259. uni.showToast({
  260. title: data.message,
  261. icon: 'none'
  262. })
  263. // 未登录
  264. if (res.statusCode == 401) {
  265. handler.$refs.login.modal = true
  266. }
  267. }
  268. },
  269. fail: (res) => {
  270. console.log('fail res', res)
  271. return false;
  272. },
  273. complete: (res => {
  274. showLoading && uni.hideLoading()
  275. })
  276. })
  277. })
  278. },
  279. };