tool.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import errorCode from './errorCode'
  2. import baseInfo from './baseInfo'
  3. import userInfo from './userInfo'
  4. import router from '@/router'
  5. import {PRICE_IS_ROUND,SERVER_API_DOMAIN} from './config'
  6. import ElementUI from 'element-ui'
  7. let tool = {
  8. /**
  9. * 设置JS存在客户端的Storage值
  10. * @param key
  11. * @param value
  12. */
  13. setStorage (key, value) {
  14. localStorage.setItem(key, value)
  15. },
  16. /**
  17. * 获取Storage值
  18. * @param key
  19. * @returns {string | null}
  20. */
  21. getStorage (key) {
  22. return localStorage.getItem(key)
  23. },
  24. /**
  25. * 移除Storage值
  26. * @param key
  27. */
  28. removeStorage (key) {
  29. localStorage.removeItem(key)
  30. },
  31. /**
  32. * 获取当前时间戳(精确到秒)
  33. * @returns {number}
  34. */
  35. getTimestamp (date = null) {
  36. let days = baseInfo.daysDiff()
  37. let dateObj
  38. if (date !== null) {
  39. dateObj = new Date(date)
  40. } else {
  41. dateObj = new Date()
  42. }
  43. return Math.round(dateObj.getTime() / 1000 + (days * 86400))
  44. },
  45. formatDate (timestamp,withTime=true) {
  46. let newDate = new Date()
  47. timestamp = parseInt(timestamp)
  48. if (timestamp) {
  49. newDate.setTime(timestamp * 1000)
  50. } else {
  51. return ''
  52. }
  53. let Y = newDate.getFullYear() + '-'
  54. let M = (newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1) + '-'
  55. let D = (newDate.getDate() < 10 ? '0' + (newDate.getDate()) : newDate.getDate()) + ' '
  56. let h = (newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours()) + ':'
  57. let m = (newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes()) + ':'
  58. let s = (newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds())
  59. if(withTime) return Y + M + D + h + m + s
  60. return Y + M + D
  61. },
  62. /**
  63. * 处理错误结果
  64. * @param error
  65. * @returns {{message: string, todo: *}}
  66. */
  67. errorHandle(error) {
  68. let message = ''
  69. let status = 0
  70. let todo
  71. if (errorCode.has(error)) {
  72. let errorResult = errorCode.get(error)
  73. message = errorResult.message
  74. status = errorResult.status ? errorResult.status : 0
  75. todo = errorResult.todo
  76. } else {
  77. message = error.message
  78. todo = null
  79. status = error.data.status ? error.data.status : 0
  80. }
  81. if (todo || status === 401) {
  82. message = todo ? 'Not authorized, please log in again.' : (message === 'Your request was made with invalid credentials.' ? 'Not authorized, please log in again.' : message)
  83. userInfo.logout()
  84. }
  85. return {message, todo}
  86. },
  87. /**
  88. * 解析URL地址
  89. * @param url
  90. * var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
  91. myURL.file; // = 'index.html'
  92. myURL.hash; // = 'top'
  93. myURL.host; // = 'abc.com'
  94. myURL.query; // = '?id=255&m=hello'
  95. myURL.params; // = Object = { id: 255, m: hello }
  96. myURL.path; // = '/dir/index.html'
  97. myURL.segments; // = Array = ['dir', 'index.html']
  98. myURL.port; // = '8080'
  99. myURL.protocol; // = 'http'
  100. myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
  101. * @returns {{source: *, protocol: string, host: string, port: string, query: string, params, file: string | *, hash: string, path: string, relative: string | *, segments: string[]}}
  102. */
  103. parseURL (url) {
  104. let a = document.createElement('a')
  105. a.href = url
  106. return {
  107. source: url,
  108. protocol: a.protocol.replace(':', ''),
  109. host: a.hostname,
  110. port: a.port,
  111. query: a.search,
  112. params: (function () {
  113. let waitUrl = a.hash.replace(/^#[\/\-_a-zA-Z0-9]+\?/, '\?') || a.search
  114. let ret = {},
  115. seg = waitUrl.replace(/^\?/, '').split('&'),
  116. len = seg.length,
  117. i = 0,
  118. s
  119. for (; i < len; i++) {
  120. if (!seg[i]) {
  121. continue
  122. }
  123. s = seg[i].split('=')
  124. ret[s[0]] = s[1]
  125. }
  126. return ret
  127. })(),
  128. file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
  129. hash: a.hash.replace('#', ''),
  130. path: a.pathname.replace(/^([^\/])/, '/$1'),
  131. relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
  132. segments: a.pathname.replace(/^\//, '').split('/')
  133. }
  134. },
  135. removeFromArr (arr, item) {
  136. for (let i = arr.length - 1; i >= 0; i--) {
  137. if (arr[i] === item) {
  138. arr.splice(i, 1)
  139. return arr
  140. }
  141. }
  142. },
  143. isInArray (arr, value) {
  144. for (let i in arr) {
  145. if (value === arr[i]) {
  146. return true
  147. }
  148. }
  149. return false
  150. },
  151. isString (val) {
  152. return typeof val === 'string' || val instanceof String
  153. },
  154. /**
  155. * 格式化金额数值为两位小数,是否四舍五入
  156. * @param val
  157. * @returns {string}
  158. */
  159. formatPrice (val) {
  160. val = Number.parseFloat(val)
  161. if (PRICE_IS_ROUND) {
  162. return val.toFixed(2)
  163. } else {
  164. val = val.toFixed(3)
  165. return val.substring(0, val.lastIndexOf('.') + 3)
  166. }
  167. },
  168. go (path) {
  169. router.push(path)
  170. },
  171. /**
  172. * 根据状态返回颜色
  173. * @param val
  174. * @returns {string}
  175. */
  176. statusType(val){
  177. switch (val){
  178. case '0':
  179. return 'info'
  180. break
  181. case '1':
  182. return 'success'
  183. break
  184. case '2':
  185. return 'warning'
  186. break
  187. case '3':
  188. return 'danger'
  189. break
  190. default:
  191. return ''
  192. }
  193. },
  194. /**
  195. * 格式化筛选数据
  196. * @param selData
  197. * @param id
  198. * @param name
  199. * @returns {Array}
  200. */
  201. filterSelectFormat(selData, id, name) {
  202. let arr=[]
  203. for (let prop in selData) {
  204. arr.push({id:selData[prop][id],name:selData[prop][name]})
  205. }
  206. return arr
  207. },
  208. /**
  209. * 日期左侧补0
  210. * @param bits
  211. * @param identifier
  212. * @param value
  213. * @returns {string}
  214. */
  215. dataLeftCompleting(bits, identifier, value){
  216. value = Array(bits + 1).join(identifier) + value;
  217. return value.slice(-bits);
  218. },
  219. /**
  220. * 获取table显示高度
  221. * @param hasStatusBar
  222. * @returns {number}
  223. */
  224. getTableHeight(hasStatusBar = false) {
  225. if (hasStatusBar) return window.innerHeight - 320
  226. return window.innerHeight - 260
  227. },
  228. /**
  229. * 是否空对象
  230. * @param obj
  231. * @returns {boolean}
  232. */
  233. isEmptyObject (obj) {
  234. let objArr = Object.keys(obj)
  235. return objArr.length === 0
  236. },
  237. /**
  238. * 向地址来看
  239. * @param paramName
  240. * @param value
  241. */
  242. insertUrlParam(paramName, value){
  243. if(typeof value === 'object'){
  244. if(tool.isEmptyObject(value)){
  245. return ;
  246. }
  247. value = JSON.stringify(value)
  248. }
  249. if(window.location.href.indexOf(paramName) === -1){
  250. if(window.location.href.indexOf('?') !== -1){
  251. window.location.href += ('&'+paramName+'='+value)
  252. } else {
  253. window.location.href += ('?'+paramName+'='+value)
  254. }
  255. } else {
  256. let searchStr = new RegExp('(\\?|&)('+paramName+'=)([^&]*)(&|$)')
  257. window.location.href = window.location.href.replace(searchStr, '$1$2'+value+'$4')
  258. }
  259. },
  260. imageRenderSoup(cover) {
  261. return cover.indexOf(SERVER_API_DOMAIN) > 0
  262. },
  263. imageRenderLang(cover) {
  264. return SERVER_API_DOMAIN + '/uploads/' + cover
  265. }
  266. }
  267. export default tool