qsk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. const prePage = (num = 2) => {
  2. let pages = getCurrentPages();
  3. let prePage = pages[pages.length - num];
  4. if (!prePage) {
  5. return null
  6. }
  7. // #ifdef H5
  8. return prePage;
  9. // #endif
  10. return prePage.$vm;
  11. }
  12. const rushPrePage = (type = false) => {
  13. if (type) {
  14. let pages = getCurrentPages();
  15. const len = pages.length
  16. if (len <= 1) {
  17. return false
  18. }
  19. pages.forEach((p, index) => {
  20. if (index >= len - 1) {
  21. return false
  22. }
  23. var prePage = p.$vm;
  24. // #ifdef H5
  25. prePage = p;
  26. // #endif
  27. try {
  28. prePage.loadData('rush')
  29. prePage.loadPageData()
  30. } catch (e) {
  31. //TODO handle the exception
  32. }
  33. })
  34. return
  35. }
  36. const pag = prePage()
  37. if (pag) {
  38. try {
  39. pag.loadData('rush')
  40. pag.loadPageData()
  41. } catch (e) {
  42. //TODO handle the exception
  43. }
  44. }
  45. return pag
  46. }
  47. // 提示信息
  48. const toast = (text, duration, mask = false, icon = "", image = "") => {
  49. uni.showToast({
  50. title: text || "出错啦~",
  51. icon: icon ? icon : 'none', // "success" "loading" "none"
  52. image: image,
  53. duration: duration || 2000,
  54. mask
  55. })
  56. }
  57. // 复制信息
  58. const copy = (str) => {
  59. return new Promise((resolve, reject) => {
  60. uni.setClipboardData({
  61. data: str,
  62. success: function() {
  63. resolve()
  64. },
  65. fail: function() {
  66. reject()
  67. }
  68. });
  69. })
  70. }
  71. // 拨打电话
  72. const call = (telNumber) => {
  73. if (!telNumber) {
  74. modal({
  75. content: '无可拨打号码!',
  76. showCancel: false
  77. })
  78. return false
  79. }
  80. uni.makePhoneCall({
  81. phoneNumber: telNumber
  82. });
  83. }
  84. // 确认信息弹框
  85. const modal = (option = null) => {
  86. const op = Object.assign({
  87. title: '提示',
  88. content: '',
  89. showCancel: true,
  90. cancelColor: "#999999",
  91. confirmColor: "#b7251a", //"#007aff", // "#007aff"
  92. confirmText: "确定",
  93. cancelText: "取消"
  94. }, option)
  95. return new Promise((resolve, reject) => {
  96. uni.showModal({
  97. title: op.title,
  98. content: op.content,
  99. showCancel: op.showCancel,
  100. cancelColor: op.cancelColor,
  101. confirmColor: op.confirmColor,
  102. confirmText: op.confirmText,
  103. cancelText: op.cancelText,
  104. success: (res) => {
  105. if (res && res.confirm) {
  106. resolve(res)
  107. } else {
  108. reject(res)
  109. }
  110. },
  111. fail: () => {
  112. reject()
  113. }
  114. })
  115. })
  116. }
  117. // 小程序微信支付
  118. const wxpay = (data) => {
  119. return new Promise((resolve, reject) => {
  120. uni.requestPayment({
  121. provider: 'wxpay', // 服务提供商
  122. timeStamp: data.timeStamp, // String(Date.now()), // 时间戳从1970年1月1日至今的秒数,即当前的时间
  123. nonceStr: data.nonceStr, // 随机字符串,长度为32个字符以下
  124. package: data.package, // 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=xx
  125. signType: 'MD5', // 签名算法,暂支持 MD5
  126. paySign: data.paySign, // 签名
  127. success: function(res) {
  128. console.log('success:' + JSON.stringify(res));
  129. resolve(res)
  130. },
  131. fail: function(err) {
  132. console.log('fail:' + JSON.stringify(err));
  133. reject(err)
  134. }
  135. });
  136. });
  137. }
  138. //判断是否登录
  139. const isLogin = (type = false) => {
  140. const token = uni.getStorageSync("token") ? true : false
  141. const url = getApp().globalData.loginPage
  142. if (type && !token) {
  143. modal({
  144. title: "未登录",
  145. content: "请在登录后再进行操作!",
  146. showCancel: true,
  147. confirmText: "马上登录"
  148. }).then(res => {
  149. href(url)
  150. }).catch(() => {})
  151. }
  152. return token
  153. }
  154. const href = (url, isVerify, type = "", data = "") => {
  155. /*
  156. isVerify:是否进行登录状态校验
  157. type: 【默认常规跳转】close【关闭所有页面再跳转】true【覆盖当前页跳转】
  158. */
  159. if (!url) {
  160. url = "/"
  161. }
  162. if (data) {
  163. url = addUrlCode(url, data)
  164. }
  165. if (isVerify) {
  166. if (!isLogin(true)) {
  167. return false
  168. }
  169. }
  170. const homePages = getApp().globalData.homePages
  171. if (url.toLowerCase().indexOf('https://') == 0 || url.toLowerCase().indexOf('https://') == 0) {
  172. // #ifdef H5
  173. location.href = url
  174. // #endif
  175. // #ifndef H5
  176. toast("不支持外链")
  177. // #endif
  178. return false
  179. }
  180. if (url.startsWith('@modal')) {
  181. var index=url.lastIndexOf('=')
  182. var str=url.substring(index+1,url.length)
  183. modal({
  184. title: "提示",
  185. content: str,
  186. showCancel: false,
  187. confirmText: "确定"
  188. }).then(res => {
  189. }).catch(() => {})
  190. return false
  191. }
  192. const isHomePage = homePages.some(item => {
  193. return url.toLowerCase().indexOf(item.toLowerCase()) >= 0
  194. })
  195. if (isHomePage) {
  196. uni.switchTab({
  197. url: url
  198. })
  199. } else {
  200. if (type == 'close') {
  201. uni.reLaunch({
  202. url: url
  203. });
  204. } else if (type) {
  205. uni.redirectTo({
  206. url: url
  207. });
  208. } else {
  209. uni.navigateTo({
  210. url: url
  211. });
  212. }
  213. }
  214. }
  215. // 返回上一页
  216. const back = () => {
  217. const pag = prePage()
  218. const loginPages = getApp().globalData.loginPages
  219. const homePage = getApp().globalData.homePage
  220. if (pag) {
  221. let currentPage = pag.route || "";
  222. const isLoginPage = loginPages.some(item => {
  223. return currentPage.toLowerCase().indexOf(item.toLowerCase()) >= 0
  224. })
  225. if (isLoginPage) {
  226. uni.switchTab({
  227. url: homePage
  228. })
  229. } else {
  230. uni.navigateBack();
  231. }
  232. } else {
  233. uni.switchTab({
  234. url: homePage
  235. })
  236. }
  237. }
  238. // 查看定位位置信息
  239. const openLocal = (item) => {
  240. var latitude = parseFloat(item.lat);
  241. var longitude = parseFloat(item.lng);
  242. if (!latitude || !longitude) {
  243. return false
  244. }
  245. uni.openLocation({
  246. latitude: latitude,
  247. longitude: longitude,
  248. name: item.name || item.mapinfo,
  249. scale: item.scale || 18,
  250. success: function() {},
  251. fail: function(res) {}
  252. })
  253. }
  254. // 小程序订阅消息
  255. const subscribeMessage = (tmplIds) => {
  256. uni.requestSubscribeMessage({
  257. tmplIds: tmplIds,
  258. success(reSub) {
  259. if (reSub.errMsg == 'requestSubscribeMessage:ok') {
  260. // 订阅完成
  261. uni.setStorageSync('subscribeMessage', true)
  262. } else {
  263. // 订阅失败
  264. uni.setStorageSync('subscribeMessage', false)
  265. }
  266. }
  267. })
  268. }
  269. // 调取url中get参数值
  270. const getUrlCode = (url, name) => {
  271. var idx = String(url).indexOf('?') + 1
  272. var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  273. var r = String(url).substr(idx).match(reg)
  274. if (r != null) return unescape(r[2])
  275. return null
  276. }
  277. // url中增加(替换)get参数值
  278. const addUrlCode = (url, data) => {
  279. if (!data || Object.keys(data).length <= 0) {
  280. return url
  281. }
  282. Object.keys(data).forEach((k, i) => {
  283. url = removeUrlCode(url, k)
  284. })
  285. var idx = String(url).indexOf('?')
  286. var len = String(url).length - 1
  287. if (idx < 0) {
  288. url += "?"
  289. } else if (idx < len) {
  290. url += "&"
  291. }
  292. Object.keys(data).forEach((k, i) => {
  293. url += i > 0 ? "&" : ""
  294. url += `${k}=${data[k]}`
  295. })
  296. return url
  297. }
  298. // 删除url中get参数值
  299. const removeUrlCode = (url, key) => {
  300. var idx = String(url).indexOf('?') + 1
  301. var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
  302. var r = String(url).substr(idx).match(reg)
  303. if (r != null) {
  304. if (r[3] && r[1]) {
  305. url = url.replace(r[0], r[3])
  306. } else {
  307. url = url.replace(r[0], "")
  308. }
  309. }
  310. return url
  311. }
  312. const isAndroid = () => {
  313. const res = uni.getSystemInfoSync();
  314. return res.platform.toLocaleLowerCase() == "android"
  315. }
  316. const isPhoneX = () => {
  317. const res = uni.getSystemInfoSync();
  318. let iphonex = false;
  319. let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
  320. const model = res.model.replace(/\s/g, "").toLowerCase()
  321. if (models.includes(model)) {
  322. iphonex = true;
  323. }
  324. return iphonex;
  325. }
  326. const getTxtKey = (str) => {
  327. var reg_g = /\{\{(.+?)\}\}/g
  328. var reg = /\{\{(\S*)\}\}/
  329. // var reg_g = new RegExp('{{(.+?)}}', 'g')
  330. // var reg = new RegExp('{{(S*)}}')
  331. // var val = String(str)
  332. const regLabel = str ? str.match(reg_g) : ''
  333. if (regLabel && regLabel.length > 0) {
  334. return regLabel.map(item => {
  335. const obj = reg.exec(String(item))
  336. return {
  337. key: obj[1],
  338. txt: obj[0]
  339. }
  340. // console.log(item, k)
  341. })
  342. }
  343. return []
  344. }
  345. /**
  346. * 获取对象下的数据,深度查询
  347. * @param {Any} data 查询数据
  348. * @param {String} _key 属性路径
  349. */
  350. const getDataAttr = (data, _key, deVal = "") => {
  351. var aKey = []
  352. if (!_key) {
  353. return data
  354. }
  355. if (!isArray(_key)) {
  356. aKey = String(_key).split(".")
  357. } else {
  358. aKey = _key
  359. }
  360. var key = aKey[0]
  361. var attr = deVal
  362. if (isArray(data)) {
  363. if (data.hasOwnProperty(key)) {
  364. if (aKey.length > 1) {
  365. aKey.shift()
  366. attr = getDataAttr(data[key], aKey)
  367. } else {
  368. attr = data[key]
  369. }
  370. }
  371. } else if (isObject(data)) {
  372. if (data.hasOwnProperty(key)) {
  373. if (aKey.length > 1) {
  374. aKey.shift()
  375. attr = getDataAttr(data[key], aKey)
  376. } else {
  377. attr = data[key]
  378. }
  379. }
  380. } else {
  381. return deVal
  382. }
  383. return attr
  384. }
  385. /**
  386. * 生成指定长度的随机字符串
  387. * @param {Number} min 最小程度
  388. * @param {Number} max 最大长度
  389. * @return {String} 返回生成的字符串
  390. */
  391. const randomString = (min, max) => {
  392. let returnStr = "",
  393. range = (max ? Math.round(Math.random() * (max - min)) + min : min),
  394. arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  395. 'k', 'l',
  396. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  397. 'H', 'I',
  398. 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
  399. ];
  400. for (let i = 0; i < range; i++) {
  401. let index = Math.round(Math.random() * (arr.length - 1));
  402. returnStr += arr[index];
  403. }
  404. return returnStr;
  405. }
  406. /**
  407. * 精确判断数据是否是 Object 类型
  408. * @param {Any} val 要判断的数据
  409. * @returns {Boolean} true:是;false:不是;
  410. */
  411. const isObject = (val) => {
  412. return Object.prototype.toString.call(val) === '[object Object]' && val !== null && val !== undefined;
  413. }
  414. /**
  415. * 判断数据是否是 Array 类型
  416. * @param {Any} val 要判断的数据
  417. * @returns {Boolean} true:是;false:不是;
  418. */
  419. const isArray = (val) => {
  420. return Object.prototype.toString.call(val) === '[object Array]';
  421. }
  422. /**
  423. * 判断数据是否是 String 类型
  424. * @param {Any} val 要判断的数据
  425. * @returns {Boolean} true:是;false:不是;
  426. */
  427. const isString = (val) => {
  428. return Object.prototype.toString.call(val) === '[object String]';
  429. }
  430. /**
  431. * 精确判断数据是否是 Date 类型
  432. * @param {Any} val 要判断的数据
  433. * @returns {Boolean} true:是;false:不是;
  434. */
  435. const isDate = (val) => {
  436. return Object.prototype.toString.call(val) === '[object Date]';
  437. }
  438. /**
  439. * 精确判断数据是否是 Function 类型
  440. * @param {Any} val 要判断的数据
  441. * @returns {Boolean} true:是;false:不是;
  442. */
  443. const isFunction = (val) => {
  444. return Object.prototype.toString.call(val) === '[object Function]';
  445. }
  446. /**
  447. * 精确判断数据是否是 Number 类型
  448. * @param {Any} val 要判断的数据
  449. * @returns {Boolean} true:是;false:不是;
  450. */
  451. const isNumber = (val) => {
  452. return Object.prototype.toString.call(val) === '[object Number]';
  453. }
  454. /**
  455. * 精确判断数据是否是 Boolean 类型
  456. * @param {Any} val 要判断的数据
  457. * @returns {Boolean} true:是;false:不是;
  458. */
  459. const isBoolean = (val) => {
  460. return Object.prototype.toString.call(val) === '[object Boolean]';
  461. }
  462. const openFile = (url) => {
  463. if (!url) {
  464. return false
  465. }
  466. uni.showLoading({
  467. title: "文件下载中..."
  468. })
  469. uni.downloadFile({
  470. url: url,
  471. success: function(res) {
  472. uni.hideLoading()
  473. var filePath = res.tempFilePath;
  474. uni.showToast({
  475. title: "文件已下载",
  476. duration: 2000,
  477. mask: false
  478. })
  479. uni.openDocument({
  480. filePath: filePath,
  481. showMenu: true,
  482. success: function(e) {
  483. console.log('打开文档成功');
  484. },
  485. fail: (e) => {
  486. console.log('打开失败', e)
  487. }
  488. });
  489. },
  490. fail: function(res) {
  491. uni.hideLoading()
  492. uni.showToast({
  493. title: "文件下载失败",
  494. duration: 2000,
  495. mask: false
  496. })
  497. }
  498. });
  499. }
  500. import * as filters from './filters.js'
  501. export default {
  502. prePage, // 上一页
  503. rushPrePage, // 刷新上一页
  504. isLogin, // 判断登录状态
  505. href, // 跳转链接
  506. back, // 返回上一页
  507. toast, // 提示框
  508. copy, // 复制
  509. call, // 拨打电话
  510. modal, // 确认提示框
  511. wxpay, // 微信支付
  512. openLocal, // 查看定位信息
  513. getUrlCode, // 获取url的GET参数
  514. addUrlCode, // url增加GET参数
  515. removeUrlCode, // 删除url中GET参数
  516. subscribeMessage, // 小程序订阅消息
  517. openFile,
  518. isAndroid,
  519. isPhoneX,
  520. randomString,
  521. ...filters,
  522. getTxtKey,
  523. getDataAttr,
  524. isObject,
  525. isArray,
  526. isString,
  527. isDate,
  528. isFunction,
  529. isNumber,
  530. isBoolean
  531. }