uniApi.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // import uniCopy from '@/js_sdk/xb-copy/uni-copy.js'; // 拷贝功能插件
  2. // import compressImage from './compressImage.js'; // 解决图片旋转90°问题
  3. // const device = uni.getSystemInfoSync();
  4. // console.log("device:======================== " + JSON.stringify(device));
  5. /*
  6. 参数说明
  7. @url
  8. 要跳转的目标地址
  9. @opt
  10. 要传给目标地址的参数
  11. 可在目标页面的onLoad生命周期函数的第一个参数中获取
  12. */
  13. // 压栈跳转页面
  14. export function navigateTo(type, url, opt) {
  15. // H5端页面跳转目前不支持动画 (浏览器性能限制)
  16. let toUrl = url;
  17. let api = 'navigateTo';
  18. toUrl = opt ? toUrl + '?' + convertObj(opt) : toUrl;
  19. switch (type) {
  20. case 1:
  21. api = 'navigateTo';
  22. break;
  23. case 2:
  24. api = 'redirectTo'; // 关闭当前页,跳转应用内某个页面
  25. break;
  26. case 3:
  27. api = 'reLaunch'; // 关闭所有页面,打开到应用内某个页面
  28. break;
  29. case 4:
  30. api = 'switchTab'; //跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
  31. break;
  32. default:
  33. api = 'navigateTo'
  34. break;
  35. }
  36. uni[api]({
  37. url: toUrl,
  38. animationType: 'slide-in-right',
  39. animationDuration: 200
  40. });
  41. }
  42. // 关闭当前页面并返回上一页面 delta 标识返回几层
  43. export function navigateBack(delta) {
  44. uni.navigateBack({
  45. delta: delta
  46. });
  47. }
  48. // setStorage 将数据存入缓存
  49. export function setStorage(key, val) {
  50. if (typeof val == 'string') {
  51. uni.setStorageSync(key, val);
  52. return val
  53. }
  54. uni.setStorageSync(key, JSON.stringify(val));
  55. }
  56. // getStorage 从缓存中读取数据
  57. export function getStorage(key) {
  58. let uu = uni.getStorageSync(key);
  59. try {
  60. if (typeof JSON.parse(uu) != 'number') {
  61. uu = JSON.parse(uu);
  62. }
  63. } catch (e) {}
  64. return uu;
  65. }
  66. // 删除缓存中的数据
  67. export function removeStorage(key) {
  68. if (key) {
  69. uni.removeStorageSync(key);
  70. }
  71. }
  72. // 将缓存中的数据清空
  73. export function clearStorage() {
  74. try {
  75. uni.clearStorageSync();
  76. } catch (e) {
  77. throw new Error('处理失败');
  78. }
  79. }
  80. // 显示Toast
  81. /*
  82. @title 最多汉字数量7个
  83. @icon success loading none
  84. */
  85. export function Toast(title, icon = 'none', obj = {}, duration = 800) {
  86. let toastData = {
  87. title: title,
  88. duration: duration,
  89. position: 'center',
  90. mask: true,
  91. icon: icon ? icon : 'none',
  92. ...obj
  93. };
  94. uni.showToast(toastData);
  95. }
  96. /*
  97. 显示loading提示框,需要手动隐藏
  98. */
  99. export function Loading(title = '正在加载...', obj = {}) {
  100. uni.showLoading({
  101. title: title,
  102. mask: true,
  103. ...obj
  104. });
  105. }
  106. // 隐藏loading
  107. export function hideLoading() {
  108. try {
  109. uni.hideLoading();
  110. } catch (e) {
  111. //TODO handle the exception
  112. throw new Error('处理失败');
  113. }
  114. }
  115. // 模态框
  116. /*
  117. 确定取消按钮的文字颜色可修改
  118. obj 对象中传入 cancelColor : rgb 即可修改取消按钮颜色
  119. obj 对象中传入 confirmColor : rgb 即可修改确认按钮颜色
  120. */
  121. export function Modal(title = '提示', content = '这是一个模态弹窗!', obj = {
  122. showCancel: true,
  123. cancelText: '取消',
  124. confirmText: '确定'
  125. }) {
  126. // #ifdef APP-PLUS
  127. obj.cancelText = '确定';
  128. obj.confirmText = '取消';
  129. // #endif
  130. return new Promise((reslove, reject) => {
  131. uni.showModal({
  132. title: title,
  133. content: content,
  134. ...obj,
  135. success: (res) => {
  136. if (res.confirm) {
  137. reslove()
  138. }
  139. if (res.cancel) {
  140. reject()
  141. }
  142. }
  143. });
  144. })
  145. }
  146. /*
  147. 显示操作菜单
  148. @itemList 操作菜单数组
  149. @itemColor 文字颜色
  150. */
  151. export function ActionSheet(itemList, itemColor = "#000000") {
  152. return new Promise((reslove, reject) => {
  153. uni.showActionSheet({
  154. itemList: itemList,
  155. itemColor: itemColor,
  156. success: (res) => {
  157. reslove(res.tapIndex);
  158. },
  159. fail: function(res) {
  160. reject(res.errMsg);
  161. }
  162. });
  163. })
  164. }
  165. //将页面滚动到目标位置。
  166. export function ScrollTo(ScrollTop) {
  167. uni.pageScrollTo({
  168. scrollTop: ScrollTop,
  169. duration: 300
  170. })
  171. }
  172. // 获取用户信息
  173. export function GetUserInfo() {
  174. return new Promise((reslove, reject) => {
  175. uni.getUserInfo({
  176. success(res) {
  177. console.log(res);
  178. reslove(res);
  179. },
  180. fail(rej) {
  181. reject(rej);
  182. }
  183. })
  184. })
  185. }
  186. // 获取用户授权信息
  187. export function Authorize(scoped = 'scope.userInfo') {
  188. return new Promise((reslove, reject) => {
  189. uni.authorize({
  190. scope: scoped,
  191. success(res) {
  192. reslove(res);
  193. },
  194. fail(rej) {
  195. reject(rej);
  196. }
  197. })
  198. })
  199. }
  200. // 将对象转换成使用 & 连接的字符串
  201. export function convertObj(opt) {
  202. let str = '';
  203. let arr = [];
  204. Object.keys(opt).forEach(item => {
  205. arr.push(`${item}=${opt[item]}`);
  206. })
  207. str = arr.join('&');
  208. return str;
  209. }
  210. // 节流函数
  211. // 节流函数
  212. export function throttle(fn, delay) {
  213. var lastArgs;
  214. var timer;
  215. var delay = delay || 200;
  216. return function(...args) {
  217. lastArgs = args;
  218. if(!timer){
  219. timer = setTimeout(()=>{
  220. timer = null;
  221. fn.apply(this, lastArgs);
  222. }, delay);
  223. }
  224. }
  225. }
  226. // 调起相机
  227. export function chooseImage(count) {
  228. return new Promise((reslove, reject) => {
  229. uni.chooseImage({
  230. count: count, //默认9
  231. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  232. sourceType: ['album', 'camera'], //从相册选择
  233. success: (res) => {
  234. reslove(res);
  235. // const tempFilePaths = res.tempFilePaths;
  236. // let tempPathList = [];
  237. // for (let i = 0; i < tempFilePaths.length; i++) {
  238. // const path = tempFilePaths[i];
  239. // const src = await compressImageHandler(path)
  240. // tempPathList.push(src);
  241. // }
  242. // reslove(tempPathList);
  243. },
  244. fail: (rej) => {
  245. reject(rej);
  246. }
  247. });
  248. })
  249. }
  250. // function compressImageHandler(src) {
  251. // // console.log('platform===' + device.platform)
  252. // const tempPath = compressImage(src, device.platform);
  253. // // console.log('tempPath-----' + tempPath);
  254. // return tempPath
  255. // }
  256. //序列化对象和数组
  257. export function serialize(data) {
  258. if (data != null && data != '') {
  259. try {
  260. return JSON.parse(JSON.stringify(data));
  261. } catch (e) {
  262. if (data instanceof Array) {
  263. return [];
  264. }
  265. return {};
  266. }
  267. }
  268. return data;
  269. }
  270. Date.prototype.format = function(fmt) {
  271. let o = {
  272. 'M+': this.getMonth() + 1, //月份
  273. 'd+': this.getDate(), //日
  274. 'h+': this.getHours(), //小时
  275. 'm+': this.getMinutes(), //分
  276. 's+': this.getSeconds(), //秒
  277. 'q+': Math.floor((this.getMonth() + 3) / 3), //季度
  278. S: this.getMilliseconds() //毫秒
  279. };
  280. if (/(y+)/.test(fmt)) {
  281. fmt = fmt.replace(RegExp.$1, String(this.getFullYear()).substr(4 - RegExp.$1.length));
  282. }
  283. for (let k in o) {
  284. if (new RegExp('(' + k + ')').test(fmt)) {
  285. fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(String(o[k]).length));
  286. }
  287. }
  288. return fmt;
  289. };
  290. //格式化日期
  291. export function formatDate(nS, format) {
  292. //日期格式化
  293. if (!nS) {
  294. return '';
  295. }
  296. format = format || 'yyyy-MM-dd hh:mm:ss';
  297. return new Date(nS).format(format);
  298. }
  299. // 图片转base64
  300. export function pathToBase64(path) {
  301. return new Promise(function(resolve, reject) {
  302. if (typeof window === 'object' && 'document' in window) {
  303. if (typeof FileReader === 'function') {
  304. var xhr = new XMLHttpRequest()
  305. xhr.open('GET', path, true)
  306. xhr.responseType = 'blob'
  307. xhr.onload = function() {
  308. if (this.status === 200) {
  309. let fileReader = new FileReader()
  310. fileReader.onload = function(e) {
  311. resolve(e.target.result)
  312. }
  313. fileReader.onerror = reject
  314. fileReader.readAsDataURL(this.response)
  315. }
  316. }
  317. xhr.onerror = reject
  318. xhr.send()
  319. return
  320. }
  321. var canvas = document.createElement('canvas')
  322. var c2x = canvas.getContext('2d')
  323. var img = new Image
  324. img.onload = function() {
  325. canvas.width = img.width
  326. canvas.height = img.height
  327. c2x.drawImage(img, 0, 0)
  328. resolve(canvas.toDataURL())
  329. canvas.height = canvas.width = 0
  330. }
  331. img.onerror = reject
  332. img.src = path
  333. return
  334. }
  335. if (typeof plus === 'object') {
  336. plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
  337. entry.file(function(file) {
  338. var fileReader = new plus.io.FileReader()
  339. fileReader.onload = function(data) {
  340. resolve(data.target.result)
  341. }
  342. fileReader.onerror = function(error) {
  343. reject(error)
  344. }
  345. fileReader.readAsDataURL(file)
  346. }, function(error) {
  347. reject(error)
  348. })
  349. }, function(error) {
  350. reject(error)
  351. })
  352. return
  353. }
  354. if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
  355. wx.getFileSystemManager().readFile({
  356. filePath: path,
  357. encoding: 'base64',
  358. success: function(res) {
  359. resolve('data:image/png;base64,' + res.data)
  360. },
  361. fail: function(error) {
  362. reject(error)
  363. }
  364. })
  365. return
  366. }
  367. reject(new Error('not support'))
  368. })
  369. }
  370. /*
  371. @value 要拷贝的内容
  372. */
  373. // export function copyText(value) {
  374. // // 条件编译,以下代码仅在H5出现
  375. // //#ifdef H5
  376. // return new Promise((reslove, reject) => {
  377. // uniCopy({
  378. // content: value,
  379. // success: (res) => {
  380. // reslove(res);
  381. // },
  382. // error: (e) => {
  383. // reject(res)
  384. // }
  385. // })
  386. // })
  387. // //#endif
  388. // // 以下代码在除H5以外的平台出现
  389. // //#ifndef H5
  390. // //#endif
  391. // }
  392. // 获取本周的第一天
  393. export function showWeekFirstDay() {
  394. var date = new Date();
  395. var weekday = date.getDay() || 7; //获取星期几,getDay()返回值是 0(周日) 到 6(周六) 之间的一个整数。0||7为7,即weekday的值为1-7
  396. date.setDate(date.getDate() - weekday + 1); //往前算(weekday-1)天,年份、月份会自动变化
  397. return formatDate(date, 'yyyy-MM-dd');
  398. }
  399. // 获取本月第一天
  400. export function showMonthFirstDay() {
  401. var MonthFirstDay = new Date().setDate(1);
  402. return formatDate(new Date(MonthFirstDay).getTime(), 'yyyy-MM-dd');
  403. }
  404. var now = new Date(); //当前日期
  405. // var nowDayOfWeek = now.getDay(); //今天本周的第几天
  406. // var nowDay = now.getDate(); //当前日
  407. var nowMonth = now.getMonth(); //当前月
  408. var nowYear = now.getYear(); //当前年
  409. nowYear += (nowYear < 2000) ? 1900 : 0; //
  410. //获得本季度的开始月份
  411. function getQuarterStartMonth() {
  412. var quarterStartMonth = 0;
  413. if(nowMonth < 3) {
  414. quarterStartMonth = 0;
  415. }
  416. if(2 < nowMonth && nowMonth < 6) {
  417. quarterStartMonth = 3;
  418. }
  419. if(5 < nowMonth && nowMonth < 9) {
  420. quarterStartMonth = 6;
  421. }
  422. if(nowMonth > 8) {
  423. quarterStartMonth = 9;
  424. }
  425. return quarterStartMonth;
  426. }
  427. //或的本季度的结束日期
  428. //获得本季度的开始日期
  429. export function getQuarterStartDate() {
  430. var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
  431. return formatDate(quarterStartDate, 'yyyy-MM-dd');
  432. }
  433. // 删除数组中重复数据
  434. export function unique(data) {
  435. data = data || [];
  436. var n = {};//存放新的数据
  437. for(var i = 0; i < data.length; i++) {
  438. var v = JSON.stringify(data[i]);
  439. if(typeof (v) == "undefined") {
  440. n[v] = 1;
  441. }
  442. }
  443. data.length = 0;
  444. for(var i in n) {
  445. data[data.length] = i;
  446. }
  447. return data;
  448. }