index.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  35. dom.style.setProperty(prop, val)
  36. }
  37. /**
  38. * 查找数组对象的某个下标
  39. * @param {Array} ary 查找的数组
  40. * @param {Functon} fn 判断的方法
  41. */
  42. // eslint-disable-next-line
  43. export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
  44. if (ary.findIndex) {
  45. return ary.findIndex(fn)
  46. }
  47. let index = -1
  48. ary.some((item: T, i: number, ary: Array<T>) => {
  49. const ret: T = fn(item, i, ary)
  50. if (ret) {
  51. index = i
  52. return ret
  53. }
  54. })
  55. return index
  56. }
  57. export const trim = (str: string) => {
  58. return str.replace(/(^\s*)|(\s*$)/g, '')
  59. }
  60. /**
  61. * @param {Date | number | string} time 需要转换的时间
  62. * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
  63. */
  64. export const formatTime = (time: Date | number | string, fmt: string) => {
  65. if (!time) return ''
  66. else {
  67. const date = new Date(time)
  68. const o = {
  69. 'M+': date.getMonth() + 1,
  70. 'd+': date.getDate(),
  71. 'H+': date.getHours(),
  72. 'm+': date.getMinutes(),
  73. 's+': date.getSeconds(),
  74. 'q+': Math.floor((date.getMonth() + 3) / 3),
  75. S: date.getMilliseconds()
  76. }
  77. if (/(y+)/.test(fmt)) {
  78. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  79. }
  80. for (const k in o) {
  81. if (new RegExp('(' + k + ')').test(fmt)) {
  82. fmt = fmt.replace(
  83. RegExp.$1,
  84. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  85. )
  86. }
  87. }
  88. return fmt
  89. }
  90. }
  91. /**
  92. * 生成随机字符串
  93. */
  94. export const toAnyString = () => {
  95. const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
  96. const r: number = (Math.random() * 16) | 0
  97. const v: number = c === 'x' ? r : (r & 0x3) | 0x8
  98. return v.toString()
  99. })
  100. return str
  101. }
  102. export const generateUUID = () => {
  103. if (typeof crypto === 'object') {
  104. if (typeof crypto.randomUUID === 'function') {
  105. return crypto.randomUUID()
  106. }
  107. if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
  108. const callback = (c: any) => {
  109. const num = Number(c)
  110. return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(
  111. 16
  112. )
  113. }
  114. return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback)
  115. }
  116. }
  117. let timestamp = new Date().getTime()
  118. let performanceNow =
  119. (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
  120. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  121. let random = Math.random() * 16
  122. if (timestamp > 0) {
  123. random = (timestamp + random) % 16 | 0
  124. timestamp = Math.floor(timestamp / 16)
  125. } else {
  126. random = (performanceNow + random) % 16 | 0
  127. performanceNow = Math.floor(performanceNow / 16)
  128. }
  129. return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  130. })
  131. }
  132. /**
  133. * 获取文件格式
  134. */
  135. export const getFileSuffix = (fileName: string) => {
  136. if (!fileName) return
  137. const arr = fileName.split('.')
  138. if (arr.length > 1) {
  139. return arr[arr.length - 1]
  140. }
  141. return
  142. }
  143. /**
  144. * element plus 的文件大小 Formatter 实现
  145. *
  146. * @param row 行数据
  147. * @param column 字段
  148. * @param cellValue 字段值
  149. */
  150. // @ts-ignore
  151. export const fileSizeFormatter = (row, column, cellValue) => {
  152. const fileSize = cellValue
  153. const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  154. const srcSize = parseFloat(fileSize)
  155. const index = Math.floor(Math.log(srcSize) / Math.log(1024))
  156. const size = srcSize / Math.pow(1024, index)
  157. const sizeStr = size.toFixed(2) //保留的小数位数
  158. return sizeStr + ' ' + unitArr[index]
  159. }
  160. /**
  161. * 将值复制到目标对象,且以目标对象属性为准,例:target: {a:1} source:{a:2,b:3} 结果为:{a:2}
  162. * @param target 目标对象
  163. * @param source 源对象
  164. */
  165. export const copyValueToTarget = (target, source) => {
  166. const newObj = Object.assign({}, target, source)
  167. // 删除多余属性
  168. Object.keys(newObj).forEach((key) => {
  169. // 如果不是target中的属性则删除
  170. if (Object.keys(target).indexOf(key) === -1) {
  171. delete newObj[key]
  172. }
  173. })
  174. // 更新目标对象值
  175. Object.assign(target, newObj)
  176. }
  177. /**
  178. * 将一个整数转换为分数保留两位小数
  179. * @param num
  180. */
  181. export const formatToFraction = (num: number | string | undefined): number => {
  182. if (typeof num === 'undefined') return 0
  183. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  184. return parseFloat((parsedNumber / 100).toFixed(2))
  185. }
  186. /**
  187. * 将一个数转换为 1.00 这样
  188. * 数据呈现的时候使用
  189. *
  190. * @param num 整数
  191. */
  192. export const floatToFixed2 = (num: number | string | undefined): string => {
  193. let str = '0.00'
  194. if (typeof num === 'undefined') {
  195. return str
  196. }
  197. const f = formatToFraction(num)
  198. const decimalPart = f.toString().split('.')[1]
  199. const len = decimalPart ? decimalPart.length : 0
  200. switch (len) {
  201. case 0:
  202. str = f.toString() + '.00'
  203. break
  204. case 1:
  205. str = f.toString() + '0'
  206. break
  207. }
  208. return str
  209. }
  210. /**
  211. * 将一个分数转换为整数
  212. * @param num
  213. */
  214. export const convertToInteger = (num: number | string | undefined): number => {
  215. if (typeof num === 'undefined') return 0
  216. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
  217. // TODO 分转元后还有小数则四舍五入
  218. return Math.round(parsedNumber * 100)
  219. }
  220. /**
  221. * 元转分
  222. */
  223. export const yuanToFen = (amount: string | number): number => {
  224. return Math.round(Number(amount) * 100)
  225. }
  226. /**
  227. * 分转元
  228. */
  229. export const fenToYuan = (amount: string | number): number => {
  230. return Number((Number(amount) / 100).toFixed(2))
  231. }
  232. /***
  233. * 复制对象值
  234. */
  235. export const copyObject = (target: object, source: object) => {
  236. const tKeys = Object.keys(target)
  237. for (let i = 0; i < tKeys.length; i++) {
  238. if (source[tKeys[i]]) {
  239. target[tKeys[i]] = source[tKeys[i]]
  240. }
  241. }
  242. }
  243. /***
  244. * 刪除对象某个Key
  245. */
  246. export const deleteKey = (target: object, key: string): object => {
  247. const nObj = {}
  248. for (const k in target) {
  249. if (k !== key) {
  250. nObj[k] = target[k]
  251. }
  252. }
  253. return nObj
  254. }
  255. /**
  256. * 格式化浮点类型数字
  257. */
  258. export const parseFloatNumber = (val: string | number | undefined): number => {
  259. if (!val) return 0
  260. return parseFloat(val.toString())
  261. }
  262. type ExpireType = {
  263. value: any
  264. expiry: number
  265. }
  266. // 存储数据(默认2小时后失效)
  267. export function setWithExpire(key, value, second = 2 * 3600): void {
  268. const now: number = new Date().getTime()
  269. const expireTime: number = second * 1000
  270. const item: ExpireType = {
  271. value: value,
  272. expiry: now + expireTime // 过期时间戳
  273. }
  274. localStorage.setItem(key, JSON.stringify(item))
  275. }
  276. // 读取数据(自动处理过期)
  277. export function getWithExpire(key): any {
  278. const itemStr: string | null = localStorage.getItem(key)
  279. if (!itemStr) return null
  280. const item: ExpireType = JSON.parse(itemStr)
  281. const now = new Date().getTime()
  282. if (now > item.expiry) {
  283. localStorage.removeItem(key) // 过期则删除
  284. return null
  285. }
  286. return item.value // 未过期返回值
  287. }