useFlattenRecords.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { computed } from 'vue';
  2. // recursion (flat tree structure)
  3. function flatRecord(record, indent, childrenColumnName, expandedKeys, getRowKey, index) {
  4. const arr = [];
  5. arr.push({
  6. record,
  7. indent,
  8. index
  9. });
  10. const key = getRowKey(record);
  11. const expanded = expandedKeys === null || expandedKeys === void 0 ? void 0 : expandedKeys.has(key);
  12. if (record && Array.isArray(record[childrenColumnName]) && expanded) {
  13. // expanded state, flat record
  14. for (let i = 0; i < record[childrenColumnName].length; i += 1) {
  15. const tempArr = flatRecord(record[childrenColumnName][i], indent + 1, childrenColumnName, expandedKeys, getRowKey, i);
  16. arr.push(...tempArr);
  17. }
  18. }
  19. return arr;
  20. }
  21. /**
  22. * flat tree data on expanded state
  23. *
  24. * @export
  25. * @template T
  26. * @param {*} data : table data
  27. * @param {string} childrenColumnName : 指定树形结构的列名
  28. * @param {Set<Key>} expandedKeys : 展开的行对应的keys
  29. * @param {GetRowKey<T>} getRowKey : 获取当前rowKey的方法
  30. * @returns flattened data
  31. */
  32. export default function useFlattenRecords(dataRef, childrenColumnNameRef, expandedKeysRef, getRowKey) {
  33. const arr = computed(() => {
  34. const childrenColumnName = childrenColumnNameRef.value;
  35. const expandedKeys = expandedKeysRef.value;
  36. const data = dataRef.value;
  37. if (expandedKeys === null || expandedKeys === void 0 ? void 0 : expandedKeys.size) {
  38. const temp = [];
  39. // collect flattened record
  40. for (let i = 0; i < (data === null || data === void 0 ? void 0 : data.length); i += 1) {
  41. const record = data[i];
  42. temp.push(...flatRecord(record, 0, childrenColumnName, expandedKeys, getRowKey.value, i));
  43. }
  44. return temp;
  45. }
  46. return data === null || data === void 0 ? void 0 : data.map((item, index) => {
  47. return {
  48. record: item,
  49. indent: 0,
  50. index
  51. };
  52. });
  53. });
  54. return arr;
  55. }