uniApi.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. export function navigateTo(type, url, opt) {
  2. let toUrl = url;
  3. let api = 'navigateTo';
  4. toUrl = opt ? toUrl + '?' + convertObj(opt) : toUrl;
  5. switch (type) {
  6. case 1:
  7. api = 'navigateTo';
  8. break;
  9. case 2:
  10. api = 'redirectTo';
  11. break;
  12. case 3:
  13. api = 'reLaunch';
  14. break;
  15. case 4:
  16. api = 'switchTab';
  17. break;
  18. default:
  19. api = 'navigateTo'
  20. break;
  21. }
  22. uni[api]({
  23. url: toUrl,
  24. animationType: 'slide-in-right',
  25. animationDuration: 200
  26. });
  27. }
  28. export function navigateBack(delta) {
  29. uni.navigateBack({
  30. delta: delta
  31. });
  32. }
  33. export function setStorage(key, val) {
  34. if (typeof val == 'string') {
  35. uni.setStorageSync(key, val);
  36. return val
  37. }
  38. uni.setStorageSync(key, JSON.stringify(val));
  39. }
  40. export function getStorage(key) {
  41. let uu = uni.getStorageSync(key);
  42. try {
  43. if (typeof JSON.parse(uu) != 'number') {
  44. uu = JSON.parse(uu);
  45. }
  46. } catch (e) {}
  47. return uu;
  48. }
  49. export function removeStorage(key) {
  50. if (key) {
  51. uni.removeStorageSync(key);
  52. }
  53. }
  54. export function clearStorage() {
  55. try {
  56. uni.clearStorageSync();
  57. } catch (e) {
  58. throw new Error('处理失败');
  59. }
  60. }
  61. export function Toast(title, icon = 'none', obj = {}, duration = 800) {
  62. let toastData = {
  63. title: title,
  64. duration: duration,
  65. position: 'center',
  66. mask: true,
  67. icon: icon ? icon : 'none',
  68. ...obj
  69. };
  70. uni.showToast(toastData);
  71. }
  72. export function Loading(title = '正在加载...', obj = {}) {
  73. uni.showLoading({
  74. title: title,
  75. mask: true,
  76. ...obj
  77. });
  78. }
  79. export function hideLoading() {
  80. try {
  81. uni.hideLoading();
  82. } catch (e) {
  83. throw new Error('处理失败');
  84. }
  85. }
  86. export function Modal(title = '提示', content = '这是一个模态弹窗!', obj = {
  87. showCancel: true,
  88. cancelText: '取消',
  89. confirmText: '确定'
  90. }) {
  91. obj.cancelText = '确定';
  92. obj.confirmText = '取消';
  93. return new Promise((reslove, reject) => {
  94. uni.showModal({
  95. title: title,
  96. content: content,
  97. ...obj,
  98. success: (res) => {
  99. if (res.confirm) {
  100. reslove()
  101. }
  102. if (res.cancel) {
  103. reject()
  104. }
  105. }
  106. });
  107. })
  108. }
  109. export function ActionSheet(itemList, itemColor = "#000000") {
  110. return new Promise((reslove, reject) => {
  111. uni.showActionSheet({
  112. itemList: itemList,
  113. itemColor: itemColor,
  114. success: (res) => {
  115. reslove(res.tapIndex);
  116. },
  117. fail: function(res) {
  118. reject(res.errMsg);
  119. }
  120. });
  121. })
  122. }
  123. export function ScrollTo(ScrollTop) {
  124. uni.pageScrollTo({
  125. scrollTop: ScrollTop,
  126. duration: 300
  127. })
  128. }
  129. export function GetUserInfo() {
  130. return new Promise((reslove, reject) => {
  131. uni.getUserInfo({
  132. success(res) {
  133. reslove(res);
  134. },
  135. fail(rej) {
  136. reject(rej);
  137. }
  138. })
  139. })
  140. }
  141. export function Authorize(scoped = 'scope.userInfo') {
  142. return new Promise((reslove, reject) => {
  143. uni.authorize({
  144. scope: scoped,
  145. success(res) {
  146. reslove(res);
  147. },
  148. fail(rej) {
  149. reject(rej);
  150. }
  151. })
  152. })
  153. }
  154. export function convertObj(opt) {
  155. let str = '';
  156. let arr = [];
  157. Object.keys(opt).forEach(item => {
  158. arr.push(`${item}=${opt[item]}`);
  159. })
  160. str = arr.join('&');
  161. return str;
  162. }
  163. export function throttle(fn, delay) {
  164. var lastArgs;
  165. var timer;
  166. var delay = delay || 200;
  167. return function(...args) {
  168. lastArgs = args;
  169. if (!timer) {
  170. timer = setTimeout(() => {
  171. timer = null;
  172. fn.apply(this, lastArgs);
  173. }, delay);
  174. }
  175. }
  176. }
  177. export function chooseImage(count) {
  178. return new Promise((reslove, reject) => {
  179. uni.chooseImage({
  180. count: count,
  181. sizeType: ['original', 'compressed'],
  182. sourceType: ['album', 'camera'],
  183. success: (res) => {
  184. reslove(res);
  185. },
  186. fail: (rej) => {
  187. reject(rej);
  188. }
  189. });
  190. })
  191. }
  192. export function serialize(data) {
  193. if (data != null && data != '') {
  194. try {
  195. return JSON.parse(JSON.stringify(data));
  196. } catch (e) {
  197. if (data instanceof Array) {
  198. return [];
  199. }
  200. return {};
  201. }
  202. }
  203. return data;
  204. }
  205. Date.prototype.format = function(fmt) {
  206. let o = {
  207. 'M+': this.getMonth() + 1,
  208. 'd+': this.getDate(),
  209. 'h+': this.getHours(),
  210. 'm+': this.getMinutes(),
  211. 's+': this.getSeconds(),
  212. 'q+': Math.floor((this.getMonth() + 3) / 3),
  213. S: this.getMilliseconds()
  214. };
  215. if (/(y+)/.test(fmt)) {
  216. fmt = fmt.replace(RegExp.$1, String(this.getFullYear()).substr(4 - RegExp.$1.length));
  217. }
  218. for (let k in o) {
  219. if (new RegExp('(' + k + ')').test(fmt)) {
  220. fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(String(o[k]).length));
  221. }
  222. }
  223. return fmt;
  224. };
  225. export function formatDate(nS, format) {
  226. if (!nS) {
  227. return '';
  228. }
  229. format = format || 'yyyy-MM-dd hh:mm:ss';
  230. return new Date(nS).format(format);
  231. }
  232. export function pathToBase64(path) {
  233. return new Promise(function(resolve, reject) {
  234. if (typeof window === 'object' && 'document' in window) {
  235. if (typeof FileReader === 'function') {
  236. var xhr = new XMLHttpRequest()
  237. xhr.open('GET', path, true)
  238. xhr.responseType = 'blob'
  239. xhr.onload = function() {
  240. if (this.status === 200) {
  241. let fileReader = new FileReader()
  242. fileReader.onload = function(e) {
  243. resolve(e.target.result)
  244. }
  245. fileReader.onerror = reject
  246. fileReader.readAsDataURL(this.response)
  247. }
  248. }
  249. xhr.onerror = reject
  250. xhr.send()
  251. return
  252. }
  253. var canvas = document.createElement('canvas')
  254. var c2x = canvas.getContext('2d')
  255. var img = new Image
  256. img.onload = function() {
  257. canvas.width = img.width
  258. canvas.height = img.height
  259. c2x.drawImage(img, 0, 0)
  260. resolve(canvas.toDataURL())
  261. canvas.height = canvas.width = 0
  262. }
  263. img.onerror = reject
  264. img.src = path
  265. return
  266. }
  267. if (typeof plus === 'object') {
  268. plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
  269. entry.file(function(file) {
  270. var fileReader = new plus.io.FileReader()
  271. fileReader.onload = function(data) {
  272. resolve(data.target.result)
  273. }
  274. fileReader.onerror = function(error) {
  275. reject(error)
  276. }
  277. fileReader.readAsDataURL(file)
  278. }, function(error) {
  279. reject(error)
  280. })
  281. }, function(error) {
  282. reject(error)
  283. })
  284. return
  285. }
  286. if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
  287. wx.getFileSystemManager().readFile({
  288. filePath: path,
  289. encoding: 'base64',
  290. success: function(res) {
  291. resolve('data:image/png;base64,' + res.data)
  292. },
  293. fail: function(error) {
  294. reject(error)
  295. }
  296. })
  297. return
  298. }
  299. reject(new Error('not support'))
  300. })
  301. }
  302. export function showWeekFirstDay() {
  303. var date = new Date();
  304. var weekday = date.getDay() || 7;
  305. date.setDate(date.getDate() - weekday + 1);
  306. return formatDate(date, 'yyyy-MM-dd');
  307. }
  308. export function showMonthFirstDay() {
  309. var MonthFirstDay = new Date().setDate(1);
  310. return formatDate(new Date(MonthFirstDay).getTime(), 'yyyy-MM-dd');
  311. }
  312. var now = new Date();
  313. var nowMonth = now.getMonth();
  314. var nowYear = now.getYear();
  315. nowYear += (nowYear < 2000) ? 1900 : 0;
  316. function getQuarterStartMonth() {
  317. var quarterStartMonth = 0;
  318. if (nowMonth < 3) {
  319. quarterStartMonth = 0;
  320. }
  321. if (2 < nowMonth && nowMonth < 6) {
  322. quarterStartMonth = 3;
  323. }
  324. if (5 < nowMonth && nowMonth < 9) {
  325. quarterStartMonth = 6;
  326. }
  327. if (nowMonth > 8) {
  328. quarterStartMonth = 9;
  329. }
  330. return quarterStartMonth;
  331. }
  332. export function getQuarterStartDate() {
  333. var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
  334. return formatDate(quarterStartDate, 'yyyy-MM-dd');
  335. }
  336. export function unique(data) {
  337. data = data || [];
  338. var n = {};
  339. for (var i = 0; i < data.length; i++) {
  340. var v = JSON.stringify(data[i]);
  341. if (typeof(v) == "undefined") {
  342. n[v] = 1;
  343. }
  344. }
  345. data.length = 0;
  346. for (var i in n) {
  347. data[data.length] = i;
  348. }
  349. return data;
  350. }