index.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // import type { Plugin } from 'vue'
  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. // 根据当前时间获取祝福语
  116. export const getGreeting = (): string => {
  117. const now = new Date()
  118. const hour = now.getHours()
  119. if (hour >= 6 && hour < 10) {
  120. return '早上好'
  121. } else if (hour >= 10 && hour < 13) {
  122. return '中午好'
  123. } else if (hour >= 13 && hour < 18) {
  124. return '下午好'
  125. } else {
  126. return '晚上好'
  127. }
  128. }
  129. // 获取当前星期几
  130. export const getDayOfWeek = (): string => {
  131. const daysOfWeek: string[] = [
  132. '星期日',
  133. '星期一',
  134. '星期二',
  135. '星期三',
  136. '星期四',
  137. '星期五',
  138. '星期六'
  139. ]
  140. const date: Date = new Date()
  141. const dayOfWeekIndex: number = date.getDay()
  142. return daysOfWeek[dayOfWeekIndex]
  143. }
  144. // 数字转金额
  145. // 作者:时光足迹
  146. // 链接:https://juejin.cn/post/7028086399601475591
  147. // 来源:稀土掘金
  148. export const formatMoney = (amount, currency = true): string => {
  149. const formatter = new Intl.NumberFormat('zh-CN', {
  150. minimumFractionDigits: 2,
  151. maximumFractionDigits: 2,
  152. useGrouping: true
  153. })
  154. const formattedAmount = formatter.format(amount)
  155. if (currency) {
  156. return `¥${formattedAmount}`
  157. }
  158. return formattedAmount
  159. }
  160. /**
  161. * 小数转折扣
  162. * 例子:0.85 -> 8.5折
  163. * 例子:0.5 -> 5折
  164. */
  165. export const convertToDiscount = (decimal: number | undefined): string => {
  166. if (decimal === undefined) {
  167. return ''
  168. }
  169. const discount = decimal * 10
  170. if (discount === 10) {
  171. return '无折扣'
  172. }
  173. return discount % 1 === 0 ? `${discount}折` : `${discount.toFixed(1)}折`
  174. }
  175. /**
  176. * 获取当前时间
  177. * 返回:yyyy-MM-dd HH:mm:ss
  178. */
  179. export const getCurrentDateTime = (): string => {
  180. const now: Date = new Date()
  181. const year: number = now.getFullYear()
  182. const month: number = now.getMonth() + 1
  183. const day: number = now.getDate()
  184. const hours: number = now.getHours()
  185. const minutes: number = now.getMinutes()
  186. const seconds: number = now.getSeconds()
  187. // 格式化为字符串
  188. const formattedDateTime = `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(
  189. minutes
  190. )}:${padZero(seconds)}`
  191. return formattedDateTime
  192. }
  193. /**
  194. * 获取当前日期
  195. * 返回:yyyy-MM-dd HH:mm:ss
  196. */
  197. export const getCurrentDate = (): string => {
  198. const now: Date = new Date()
  199. const year: number = now.getFullYear()
  200. const month: number = now.getMonth() + 1
  201. const day: number = now.getDate()
  202. // 格式化为字符串
  203. const formattedDate = `${year}-${padZero(month)}-${padZero(day)}`
  204. return formattedDate
  205. }
  206. // 辅助函数:在数字小于10时,在前面补零
  207. export const padZero = (num: number): string => {
  208. return num < 10 ? `0${num}` : `${num}`
  209. }
  210. // 将base64编码的字符串转换为文件
  211. export const base64ToFile = (dataURI, filename): File => {
  212. const arr = dataURI.split(',')
  213. const mime = arr[0].match(/:(.*?);/)[1]
  214. const bstr = atob(arr[1])
  215. let n = bstr.length
  216. const u8arr = new Uint8Array(n)
  217. while (n--) {
  218. u8arr[n] = bstr.charCodeAt(n)
  219. }
  220. return new File([u8arr], filename, { type: mime })
  221. }
  222. // 将指定索引的元素移动到目标索引的函数
  223. export const moveElementToIndex = (array: any[], fromIndex: number, toIndex: number) => {
  224. const clonedArray = [...array] // 克隆数组以避免修改原始数组
  225. if (
  226. fromIndex >= 0 &&
  227. fromIndex < clonedArray.length &&
  228. toIndex >= 0 &&
  229. toIndex < clonedArray.length
  230. ) {
  231. const [element] = clonedArray.splice(fromIndex, 1) // 移除指定索引的元素
  232. clonedArray.splice(toIndex, 0, element) // 将元素插入目标索引位置
  233. }
  234. return clonedArray
  235. }