sugar.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. export const log = console.log
  2. export const upx2px = val => uni.upx2px(parseInt(val))
  3. export const toast = (title, options = { duration: 2000, icon: 'none' }) => uni.showToast({ title, fail: console.log, ...options })
  4. export const makePhoneCall = phoneNumber => uni.makePhoneCall({ phoneNumber, fail: console.log });
  5. export const previewImage = (urls, current, options) => uni.previewImage({ urls, current, fail: console.log, ...options });
  6. export const copy = (str, options) => uni.setClipboardData({ data: String(str), fail: console.log, ...options })
  7. export const openMap = (lng, lat, name, address, options) => uni.openLocation({ longitude: parseFloat(lng), latitude: parseFloat(lat), name, address, fail: console.log, ...options })
  8. export const setStorage = (key, value) => uni.setStorageSync(key, value)
  9. // 判断空值
  10. export const isEmpty = value => {
  11. if (value === null || value === undefined || value === '') {
  12. return true;
  13. }
  14. if (Array.isArray(value)) {
  15. return value.length === 0;
  16. }
  17. if (typeof value === 'object') {
  18. return Object.keys(value).length === 0;
  19. }
  20. return false;
  21. }
  22. // 返回对象属性为空的 property path
  23. const getEmptyValuePropertyPath = (obj, excludedKeys = []) => {
  24. for (let key in obj) {
  25. if (obj.hasOwnProperty(key) && !excludedKeys.includes(key)) {
  26. let value = obj[key];
  27. if (Array.isArray(value)) {
  28. // 判断是否为数组对象
  29. for (let item of value) {
  30. const childrenKey = getEmptyValuePropertyPath(item, excludedKeys)
  31. if (item instanceof Object && childrenKey) {
  32. return key + '.' + childrenKey;
  33. }
  34. }
  35. if (value.length === 0) {
  36. return key;
  37. }
  38. } else if (value instanceof Object) {
  39. const childrenKey = getEmptyValuePropertyPath(value, excludedKeys)
  40. if (childrenKey) {
  41. return key + '.' + childrenKey;
  42. }
  43. } else if (isEmpty(value)) {
  44. return key;
  45. }
  46. }
  47. }
  48. return null;
  49. }
  50. // 有无空字段
  51. export const hasEmptyField = (obj, excludedKeys = []) => getEmptyValuePropertyPath(obj, excludedKeys)
  52. // 跳转企业微信客服
  53. export const toCustomerService = (corpId, url) => {
  54. // #ifdef MP-WEIXIN
  55. wx.openCustomerServiceChat({
  56. extInfo: {
  57. url
  58. },
  59. corpId,
  60. success(res) {},
  61. fail: (err) => {
  62. console.log(err);
  63. uni.showToast({
  64. title: err?.errMsg
  65. })
  66. }
  67. })
  68. // #endif
  69. // #ifdef APP
  70. plus.share.getServices(services => {
  71. const sweixin = services.find(i => i.id === 'weixin')
  72. if (sweixin) {
  73. sweixin.openCustomerServiceChat({
  74. corpid: corpId,
  75. url,
  76. }, res => {
  77. console.log("success", JSON.stringify(res))
  78. }, err => {
  79. console.log("error", JSON.stringify(err))
  80. })
  81. } else {
  82. plus.nativeUI.alert('当前环境不支持微信操作!')
  83. }
  84. }, function() {
  85. uni.showToast({ title: "获取服务失败,不支持该操作。" + JSON.stringify(e), icon: 'error' })
  86. })
  87. // #endif
  88. // #ifdef H5
  89. window.location.href = url
  90. // #endif
  91. }
  92. // 保存图片
  93. export const saveImage = async (url, tips = true) => {
  94. try {
  95. console.log('saveImage', url);
  96. // #ifdef H5
  97. const link = document.createElement('a');
  98. link.href = url;
  99. link.download = url.substring(url.lastIndexOf('/') + 1);
  100. document.body.appendChild(link);
  101. link.click();
  102. document.body.removeChild(link);
  103. // #endif
  104. // #ifndef H5
  105. if (url.startsWith('http')) {
  106. const { statusCode, tempFilePath: filePath } = await uni.downloadFile({
  107. url
  108. })
  109. if (statusCode == 200) {
  110. await uni.saveImageToPhotosAlbum({
  111. filePath
  112. })
  113. } else {
  114. throw Error('图片下载失败')
  115. }
  116. } else {
  117. await uni.saveImageToPhotosAlbum({
  118. filePath: url
  119. })
  120. }
  121. // #endif
  122. tips && uni.showToast({
  123. title: '保存成功',
  124. icon: 'success'
  125. })
  126. } catch (e) {
  127. console.log(e);
  128. tips && uni.showToast({
  129. title: '保存失败',
  130. icon: 'error'
  131. })
  132. }
  133. }
  134. // 获取页面通信管道(支持 vue2 需绑定this)
  135. export const pageEvent = function() {
  136. // #ifdef VUE2
  137. return this.getOpenerEventChannel()
  138. // #endif
  139. // #ifdef VUE3
  140. console.error('vue3 不支持这种使用方式')
  141. // #endif
  142. }
  143. // 对象转查询字符串
  144. export const object2queryStr = (obj) => {
  145. if (!obj) return obj
  146. return Object.keys(obj).reduce((val, key) => {
  147. return `${val}${key}=${obj[key]}&`
  148. }, '?').slice(0, -1)
  149. }
  150. // html 转纯文本
  151. export const html2text = (html) => {
  152. return String(html).replace(/<[^>]+>|&[^;]+;/g, '').replace(/\s+/g, ' ').trim();
  153. }
  154. /**
  155. * @Func dataMask
  156. * @Desc 数据脱敏
  157. * @param {String} str 字符串
  158. * @param {Number} head 头部保留位数
  159. * @param {Number} tail 尾部保留位数
  160. * @return {String} 脱敏后的数据
  161. */
  162. export const dataMask = (str, head, tail) => {
  163. if (!str) return str
  164. const arr = String(str).split('')
  165. tail = arr.length - tail
  166. if (head < 0) head = 0
  167. if (head > tail) return str
  168. for (let i = head; i < tail; i++) {
  169. arr[i] = '*'
  170. }
  171. return arr.join('')
  172. }
  173. // 查询元素信息
  174. export const queryElementRect = function(selector) {
  175. if (Array.isArray(selector)) return Promise.all(selector.map(i => queryElementRect.call(this, i)))
  176. return new Promise(resolve => {
  177. uni.createSelectorQuery()
  178. .in(this).select(selector)
  179. .boundingClientRect(resolve)
  180. .exec();
  181. })
  182. }