【自用】Vue專案中常用工具類:判空、非空、複製物件、使用遞迴將陣列轉為樹形結構、隨機生成指定長度的某進位制數
阿新 • • 發佈:2021-08-09
export class Tool { /** * 空校驗 null或""都返回true */ public static isEmpty (obj: any) { if ((typeof obj === 'string')) { return !obj || obj.replace(/\s+/g, "") === "" } else { return (!obj || JSON.stringify(obj) === "{}" || obj.length === 0); } } /** * 非空校驗 */ public static isNotEmpty (obj: any) { return !this.isEmpty(obj); } /** * 物件複製 * @param obj */ public static copy (obj: any) { if (Tool.isNotEmpty(obj)) { return JSON.parse(JSON.stringify(obj)); } } /** * 使用遞迴將陣列轉為樹形結構 * 父ID屬性為parent */ public static array2Tree (array: any, parentId: number) { if (Tool.isEmpty(array)) { return []; } const result = []; for (let i = 0; i < array.length; i++) { const c = array[i]; // console.log(Number(c.parent), Number(parentId)); if (Number(c.parent) === Number(parentId)) { result.push(c); // 遞迴檢視當前節點對應的子節點 const children = Tool.array2Tree(array, c.id); if (Tool.isNotEmpty(children)) { c.children = children; } } } return result; } /** * 隨機生成[len]長度的[radix]進位制數 * @param len * @param radix 預設62 * @returns {string} */ public static uuid (len: number, radix = 62) { const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); const uuid = []; radix = radix || chars.length; for (let i = 0; i < len; i++) { uuid[i] = chars[0 | Math.random() * radix]; } return uuid.join(''); } }
使用方法:
<script lang="ts"> import {Tool} from "@/utils/tool"; export default defineComponent({ // 省略其他內容 // 元件載入完成後執行 setup() { const edit = (record: any) => { modalVisible.value = true; // 複製物件值,防止影響表單響應式資料 ebook.value = Tool.copy(record); }; } }) </script>