const utils = { fontSize(res) { let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth if (!clientWidth) return let fontSize = clientWidth / 1920 return res * fontSize }, // 滚动到底部 scorllToTableBottom: (tableRef) => { setTimeout(() => { this.$nextTick(() => { const table = this.$refs[tableRef] if (table) { table.bodyWrapper.scrollTop = table.bodyWrapper.scrollHeight } }) }, 200) }, /** * 随机生成id */ uuid: (hasHyphen = false) => { return ( hasHyphen ? 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' : 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx' ).replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0 const v = c == 'x' ? r : (r & 0x3) | 0x8 return v.toString(16) }) }, // 格式化文件大小 formatFileSize(bytes: number) { if (bytes === undefined || bytes === null) return '-' const k = 1024 const sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] if (bytes < k) return '0 KB' // 最小单位为 kb const i = Math.floor(Math.log(bytes) / Math.log(k)) const size = bytes / Math.pow(k, i) const formattedSize = parseFloat(size.toFixed(2)) return `${formattedSize} ${sizes[i - 1]}` // i-1 因为 kb 是最小单位 }, // 格式化时间为时分秒 formatTime(time: number) { const hours = Math.floor(time / 3600) const minutes = Math.floor((time % 3600) / 60) const seconds = Math.floor(time % 60) return `${hours}小时${minutes}分${seconds}秒` }, /** * 从树形数据中根据id匹配节点,并返回该节点及其所有子节点的id数组。常用于表格数据通过树形目录进行筛选 * @param {Array} tree - 树形数据。 * @param {number | string} targetId - 目标节点的id。 * @param {'string' | 'array'} type - 返回结果为逗号分隔字符串还是数组。 * @return {String | Array} 包含匹配节点及其所有子节点的id的逗号分隔字符串或数组。 * @example * findNodeAndChildrenIds([ * {id:'',children:[{id:'1'} , {id:'2'}]} * ],'xxx') */ findNodeAndChildrenIds(tree = [], targetId = '', type = 'string') { let ids: (string | number)[] = [] // 收集节点及其子节点的所有id function collectIds(node: any) { ids.push(node.id) if (node.children && node.children.length > 0) { for (const child of node.children) { collectIds(child) } } } // 遍历树形数据找到目标节点 function traverse(nodes: any[]) { for (const node of nodes) { if (node.id === targetId) { // 找到目标节点,开始收集id collectIds(node) return true // 停止遍历,因为已经找到目标节点 } if (node.children && node.children.length > 0) { const found = traverse(node.children) if (found) return true // 如果在子节点中找到目标,停止遍历 } } return false // 当前分支没有找到目标节点 } traverse(tree) return type === 'string' ? ids.join(',') : ids } } export default utils