useLazyKVMap.js 972 B

12345678910111213141516171819202122232425262728293031
  1. import { watch, shallowRef } from 'vue';
  2. export default function useLazyKVMap(dataRef, childrenColumnNameRef, getRowKeyRef) {
  3. const mapCacheRef = shallowRef({});
  4. watch([dataRef, childrenColumnNameRef, getRowKeyRef], () => {
  5. const kvMap = new Map();
  6. const getRowKey = getRowKeyRef.value;
  7. const childrenColumnName = childrenColumnNameRef.value;
  8. /* eslint-disable no-inner-declarations */
  9. function dig(records) {
  10. records.forEach((record, index) => {
  11. const rowKey = getRowKey(record, index);
  12. kvMap.set(rowKey, record);
  13. if (record && typeof record === 'object' && childrenColumnName in record) {
  14. dig(record[childrenColumnName] || []);
  15. }
  16. });
  17. }
  18. /* eslint-enable */
  19. dig(dataRef.value);
  20. mapCacheRef.value = {
  21. kvMap
  22. };
  23. }, {
  24. deep: true,
  25. immediate: true
  26. });
  27. function getRecordByKey(key) {
  28. return mapCacheRef.value.kvMap.get(key);
  29. }
  30. return [getRecordByKey];
  31. }