util.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import CONSTANT from '@/constant'
  2. import { mobileReg } from '@/utils/tools/validate'
  3. import { getMiniAppUrl, isWxBrowser } from '@/utils/common'
  4. // 是否为空
  5. const isEmpty = (val) => {
  6. if (val instanceof Array) {
  7. if (val.length === 0) return true
  8. } else if (val instanceof Object) {
  9. if (!Object.keys(val).length) return true
  10. } else {
  11. if (val === 'null' || val === null || val === 'undefined' || val === undefined || val === '') return true
  12. return false
  13. }
  14. return false
  15. }
  16. /**
  17. * 深拷贝对象
  18. * @param {要拷贝对象} obj
  19. */
  20. export const copyObject = obj => {
  21. let str,
  22. newobj = Array.isArray(obj) === true ? [] : {};
  23. if (typeof obj !== "object") {
  24. return;
  25. } else if (JSON) {
  26. (str = JSON.stringify(obj)), //系列化对象
  27. (newobj = JSON.parse(str)); //还原
  28. } else {
  29. for (let i in obj) {
  30. newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
  31. }
  32. }
  33. return newobj;
  34. };
  35. // 截取图片上传字符串
  36. const imgSubstr = (val) => {
  37. if (isEmpty(val)) return []
  38. if (isArray(val)) {
  39. return val.map(e => {
  40. let index = e.indexOf('/uploads/')
  41. e = e.substring(index)
  42. return e
  43. })
  44. } else {
  45. let index = val.indexOf('/uploads/')
  46. return val.substring(index)
  47. }
  48. }
  49. // 是否为数组
  50. const isArray = (arr) => {
  51. return (typeof arr == 'object') && arr.constructor == Array
  52. }
  53. // 是否为字符串
  54. const isString = (str) => {
  55. return (typeof str == 'string') && str.constructor == String
  56. }
  57. // 是否为对象
  58. const isObject = (obj) => {
  59. return (typeof obj == 'object') && obj.constructor == Object
  60. }
  61. // 是否为数字
  62. const isNumber = (num) => {
  63. return (typeof num == 'number') && num.constructor == Number
  64. }
  65. // 是否为日期类型
  66. const isDate = (date) => {
  67. return (typeof date == 'object') && date.constructor == Date
  68. }
  69. // 是否为函数
  70. const isFunction = (obj) => {
  71. return (typeof obj == 'object') && obj.constructor == Function
  72. }
  73. const checkMobile = (num) => {
  74. return mobileReg.test(num)
  75. }
  76. const checkName = (str) => {
  77. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str)
  78. }
  79. /** *
  80. * 检查登录
  81. * @parmas query 拼接得参数对象
  82. * @parmas isFrist 为true时开头为&
  83. */
  84. export async function getCheckLogin() {
  85. let status = false
  86. let token = uni.getStorageSync('token')
  87. if (token) {
  88. status = true
  89. } else {
  90. // #ifdef H5
  91. if (isWxBrowser()) {
  92. let option = JSON.parse(uni.getStorageSync('currentQuery')) || {}
  93. console.log('option', option)
  94. // console.log('option', getMiniAppUrl(option, true))
  95. // return false
  96. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(getMiniAppUrl(option, true))}`
  97. } else {
  98. // uni.showToast({
  99. // title: '请用微信浏览器打开!',
  100. // icon: 'none',
  101. // mask: true
  102. // })
  103. }
  104. // #endif
  105. // #ifndef H5
  106. // #endif
  107. }
  108. return status
  109. }
  110. export const floatFormat = (f, n) => {
  111. let m = Math.pow(10, n)
  112. return parseInt(f * m, 10) / m
  113. }
  114. /** *
  115. * 对象参数转为url参数
  116. * @parmas query 拼接得参数对象
  117. * @parmas isFrist 为true时开头为&
  118. */
  119. export const parse = (query, isFrist = false) => {
  120. let str = Object.keys(query)
  121. .filter(key => !isEmpty(query[key]))
  122. .reduce((result, key) => {
  123. const value = query[key]
  124. // in查询特殊处理
  125. if (Array.isArray(value) && !isEmpty(value)) {
  126. return `${result}&${value.reduce((val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`, '')}`
  127. }
  128. // between查询做特殊处理
  129. if (typeof value === 'object' && !isEmpty(value)) {
  130. const [start, end] = value
  131. return `${result}&${key}[]=${start}&${key}[]=${end}`
  132. }
  133. return `${result}&${key}=${value}`
  134. }, '')
  135. return isFrist ? str : str.replace(/^&/, '?')
  136. }
  137. /** *
  138. * 全局时间转换
  139. * @parmas num 时间戳默认为11位时间戳
  140. * @parmas fmt 默认转换的时间格式
  141. * @parmas all 为true时time为13位时间戳
  142. */
  143. export const $formatDate = (num, fmt = 'YYYY-MM-DD HH:mm', all) => {
  144. num = all ? num : num * 1000
  145. let date = new Date()
  146. date.setTime(num)
  147. let o = {
  148. 'M+': date.getMonth() + 1,
  149. 'D+': date.getDate(),
  150. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  151. 'H+': date.getHours(),
  152. 'm+': date.getMinutes(),
  153. 's+': date.getSeconds(),
  154. 'q+': Math.floor((date.getMonth() + 3) / 3),
  155. 'S': date.getMilliseconds()
  156. }
  157. let week = {
  158. '0': '\u65e5',
  159. '1': '\u4e00',
  160. '2': '\u4e8c',
  161. '3': '\u4e09',
  162. '4': '\u56db',
  163. '5': '\u4e94',
  164. '6': '\u516d'
  165. }
  166. if (/(Y+)/.test(fmt)) {
  167. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  168. }
  169. if (/(E+)/.test(fmt)) {
  170. fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  171. }
  172. for (let k in o) {
  173. if (new RegExp('(' + k + ')').test(fmt)) {
  174. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  175. }
  176. }
  177. return fmt
  178. }
  179. /** *
  180. * 全局公共按钮跳转
  181. * @parmas item.funtion 为可执行函数
  182. * @parmas item.url 为跳转的路径
  183. * @parmas item.query 为跳转携带的参数
  184. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo, 3为reLaunch, 4为switchTab
  185. */
  186. export const pageTo = (item) => {
  187. if (isNumber(item)) {
  188. uni.navigateBack({
  189. delta: item
  190. })
  191. }
  192. if (isString(item)) {
  193. uni.navigateTo({
  194. url: item
  195. })
  196. return false
  197. }
  198. if (item.funtion) {
  199. item.funtion()
  200. }
  201. if (item.url) {
  202. let query = item.query ? parse(item.query) : ''
  203. let allUrl = `${item.url}${query}`
  204. if (item.type == 2) {
  205. uni.redirectTo({
  206. url: allUrl
  207. })
  208. } else if (item.type == 3) {
  209. uni.reLaunch({
  210. url: allUrl
  211. })
  212. } else if (item.type == 4) {
  213. console.log('item', item)
  214. console.log('switch shop', item.query)
  215. uni.setStorageSync('switchTabQuery', item.query)
  216. if (item.query.account) {
  217. uni.setStorageSync('account', item.query.account)
  218. }
  219. uni.switchTab({
  220. url: item.url
  221. })
  222. } else {
  223. uni.navigateTo({
  224. url: allUrl
  225. })
  226. }
  227. }
  228. }
  229. /** *
  230. * 是否登录
  231. */
  232. export const isLogin = () => {
  233. let token = uni.getStorageSync('token')
  234. if (token) {
  235. return true
  236. }
  237. return false
  238. }
  239. /**
  240. * 去重
  241. * 姜枫 2021.05.05
  242. * **/
  243. export const unique = (arr) => {
  244. for(var i=0; i<arr.length; i++){
  245. for(var j=i+1; j<arr.length; j++){
  246. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  247. arr.splice(j,1);
  248. j--;
  249. }
  250. }
  251. }
  252. return arr;
  253. };
  254. export default {
  255. isEmpty,
  256. copyObject,
  257. imgSubstr,
  258. isArray,
  259. parse,
  260. checkMobile,
  261. checkName,
  262. $formatDate,
  263. floatFormat,
  264. pageTo,
  265. isLogin,
  266. getCheckLogin,
  267. unique,
  268. }