index.ts 6.9 KB

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