index.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { toNumber } from 'lodash-es'
  2. /**
  3. *
  4. * @param component 需要注册的组件
  5. * @param alias 组件别名
  6. * @returns any
  7. */
  8. export const withInstall = <T>(component: T, alias?: string) => {
  9. const comp = component as any
  10. comp.install = (app: any) => {
  11. app.component(comp.name || comp.displayName, component)
  12. if (alias) {
  13. app.config.globalProperties[alias] = component
  14. }
  15. }
  16. return component as T & Plugin
  17. }
  18. /**
  19. * @param str 需要转下划线的驼峰字符串
  20. * @returns 字符串下划线
  21. */
  22. export const humpToUnderline = (str: string): string => {
  23. return str.replace(/([A-Z])/g, '-$1').toLowerCase()
  24. }
  25. /**
  26. * @param str 需要转驼峰的下划线字符串
  27. * @returns 字符串驼峰
  28. */
  29. export const underlineToHump = (str: string): string => {
  30. if (!str) return ''
  31. return str.replace(/\-(\w)/g, (_, letter: string) => {
  32. return letter.toUpperCase()
  33. })
  34. }
  35. /**
  36. * 驼峰转横杠
  37. */
  38. export const humpToDash = (str: string): string => {
  39. return str.replace(/([A-Z])/g, '-$1').toLowerCase()
  40. }
  41. export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  42. dom.style.setProperty(prop, val)
  43. }
  44. /**
  45. * 查找数组对象的某个下标
  46. * @param {Array} ary 查找的数组
  47. * @param {Functon} fn 判断的方法
  48. */
  49. // eslint-disable-next-line
  50. export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
  51. if (ary.findIndex) {
  52. return ary.findIndex(fn)
  53. }
  54. let index = -1
  55. ary.some((item: T, i: number, ary: Array<T>) => {
  56. const ret: T = fn(item, i, ary)
  57. if (ret) {
  58. index = i
  59. return ret
  60. }
  61. })
  62. return index
  63. }
  64. export const trim = (str: string) => {
  65. return str.replace(/(^\s*)|(\s*$)/g, '')
  66. }
  67. /**
  68. * @param {Date | number | string} time 需要转换的时间
  69. * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
  70. */
  71. export function formatTime(time: Date | number | string, fmt: string) {
  72. if (!time) return ''
  73. else {
  74. const date = new Date(time)
  75. const o = {
  76. 'M+': date.getMonth() + 1,
  77. 'd+': date.getDate(),
  78. 'H+': date.getHours(),
  79. 'm+': date.getMinutes(),
  80. 's+': date.getSeconds(),
  81. 'q+': Math.floor((date.getMonth() + 3) / 3),
  82. S: date.getMilliseconds()
  83. }
  84. if (/(y+)/.test(fmt)) {
  85. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  86. }
  87. for (const k in o) {
  88. if (new RegExp('(' + k + ')').test(fmt)) {
  89. fmt = fmt.replace(
  90. RegExp.$1,
  91. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  92. )
  93. }
  94. }
  95. return fmt
  96. }
  97. }
  98. /**
  99. * 生成随机字符串
  100. */
  101. export function toAnyString() {
  102. const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
  103. const r: number = (Math.random() * 16) | 0
  104. const v: number = c === 'x' ? r : (r & 0x3) | 0x8
  105. return v.toString()
  106. })
  107. return str
  108. }
  109. /**
  110. * 首字母大写
  111. */
  112. export function firstUpperCase(str: string) {
  113. return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
  114. }
  115. export const generateUUID = () => {
  116. if (typeof crypto === 'object') {
  117. if (typeof crypto.randomUUID === 'function') {
  118. return crypto.randomUUID()
  119. }
  120. if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
  121. const callback = (c: any) => {
  122. const num = Number(c)
  123. return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(
  124. 16
  125. )
  126. }
  127. return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
  128. }
  129. }
  130. let timestamp = new Date().getTime()
  131. let performanceNow =
  132. (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
  133. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  134. let random = Math.random() * 16
  135. if (timestamp > 0) {
  136. random = (timestamp + random) % 16 | 0
  137. timestamp = Math.floor(timestamp / 16)
  138. } else {
  139. random = (performanceNow + random) % 16 | 0
  140. performanceNow = Math.floor(performanceNow / 16)
  141. }
  142. return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  143. })
  144. }
  145. /**
  146. * element plus 的文件大小 Formatter 实现
  147. *
  148. * @param row 行数据
  149. * @param column 字段
  150. * @param cellValue 字段值
  151. */
  152. // @ts-ignore
  153. export const fileSizeFormatter = (row, column, cellValue) => {
  154. const fileSize = cellValue
  155. const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  156. const srcSize = parseFloat(fileSize)
  157. const index = Math.floor(Math.log(srcSize) / Math.log(1024))
  158. const size = srcSize / Math.pow(1024, index)
  159. const sizeStr = size.toFixed(2) //保留的小数位数
  160. return sizeStr + ' ' + unitArr[index]
  161. }
  162. /**
  163. * 将值复制到目标对象,且以目标对象属性为准,例:target: {a:1} source:{a:2,b:3} 结果为:{a:2}
  164. * @param target 目标对象
  165. * @param source 源对象
  166. */
  167. export const copyValueToTarget = (target, source) => {
  168. const newObj = Object.assign({}, target, source)
  169. // 删除多余属性
  170. Object.keys(newObj).forEach((key) => {
  171. // 如果不是target中的属性则删除
  172. if (Object.keys(target).indexOf(key) === -1) {
  173. delete newObj[key]
  174. }
  175. })
  176. // 更新目标对象值
  177. Object.assign(target, newObj)
  178. }
  179. /**
  180. * 将一个整数转换为分数保留两位小数
  181. * @param num
  182. */
  183. export const formatToFraction = (num: number | string | undefined): number => {
  184. if (typeof num === 'undefined') return 0
  185. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  186. return parseFloat((parsedNumber / 100).toFixed(2))
  187. }
  188. /**
  189. * 将一个数转换为 1.00 这样
  190. * 数据呈现的时候使用
  191. *
  192. * @param num 整数
  193. */
  194. export const floatToFixed2 = (num: number | string | undefined): string => {
  195. let str = '0.00'
  196. if (typeof num === 'undefined') {
  197. return str
  198. }
  199. const f = formatToFraction(num)
  200. const decimalPart = f.toString().split('.')[1]
  201. const len = decimalPart ? decimalPart.length : 0
  202. switch (len) {
  203. case 0:
  204. str = f.toString() + '.00'
  205. break
  206. case 1:
  207. str = f.toString() + '0'
  208. break
  209. case 2:
  210. str = f.toString()
  211. break
  212. }
  213. return str
  214. }
  215. /**
  216. * 将一个分数转换为整数
  217. * @param num
  218. */
  219. export const convertToInteger = (num: number | string | undefined): number => {
  220. if (typeof num === 'undefined') return 0
  221. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  222. // TODO 分转元后还有小数则四舍五入
  223. return Math.round(parsedNumber * 100)
  224. }
  225. /**
  226. * 元转分
  227. */
  228. export const yuanToFen = (amount: string | number): number => {
  229. return convertToInteger(amount)
  230. }
  231. /**
  232. * 分转元
  233. */
  234. export const fenToYuan = (price: string | number): number => {
  235. return formatToFraction(price)
  236. }
  237. /**
  238. * 计算环比
  239. *
  240. * @param value 当前数值
  241. * @param reference 对比数值
  242. */
  243. export const calculateRelativeRate = (value?: number, reference?: number) => {
  244. // 防止除0
  245. if (!reference) return 0
  246. return ((100 * ((value || 0) - reference)) / reference).toFixed(0)
  247. }
  248. /**
  249. * 获取链接的参数值
  250. * @param key 参数键名
  251. * @param urlStr 链接地址,默认为当前浏览器的地址
  252. */
  253. export const getUrlValue = (key: string, urlStr: string = location.href): string => {
  254. if (!urlStr || !key) return ''
  255. const url = new URL(decodeURIComponent(urlStr))
  256. return url.searchParams.get(key) ?? ''
  257. }
  258. /**
  259. * 获取链接的参数值(值类型)
  260. * @param key 参数键名
  261. * @param urlStr 链接地址,默认为当前浏览器的地址
  262. */
  263. export const getUrlNumberValue = (key: string, urlStr: string = location.href): number => {
  264. return toNumber(getUrlValue(key, urlStr))
  265. }