fix: refs #6919 refactor FormModel component state management and data handling
gitea/salix-front/pipeline/pr-dev There was a failure building this commit Details

This commit is contained in:
Jorge Penadés 2025-01-28 18:01:20 +01:00
parent abe894c8bd
commit 1d80d75e6a
1 changed files with 16 additions and 12 deletions

View File

@ -97,7 +97,7 @@ const $props = defineProps({
});
const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed(
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`
() => $props.model ?? `formModel_${route?.meta?.title ?? route.name}`,
).value;
const componentIsRendered = ref(false);
const arrayData = useArrayData(modelValue);
@ -105,8 +105,8 @@ const isLoading = ref(false);
// Si elegimos observar los cambios del form significa que inicialmente las actions estaran deshabilitadas
const isResetting = ref(false);
const hasChanges = ref(!$props.observeFormChanges);
const originalData = ref({});
const formData = computed(() => state.get(modelValue));
const originalData = computed(() => state.get(modelValue));
const formData = ref({});
const defaultButtons = computed(() => ({
save: {
dataCy: 'saveDefaultBtn',
@ -127,8 +127,6 @@ const defaultButtons = computed(() => ({
}));
onMounted(async () => {
originalData.value = JSON.parse(JSON.stringify($props.formInitialData ?? {}));
nextTick(() => (componentIsRendered.value = true));
// Podemos enviarle al form la estructura de data inicial sin necesidad de fetchearla
@ -148,7 +146,7 @@ onMounted(async () => {
JSON.stringify(newVal) !== JSON.stringify(originalData.value);
isResetting.value = false;
},
{ deep: true }
{ deep: true },
);
}
});
@ -156,16 +154,24 @@ onMounted(async () => {
if (!$props.url)
watch(
() => arrayData.store.data,
(val) => updateAndEmit('onFetch', val)
(val) => updateAndEmit('onFetch', val),
);
watch(
originalData,
(val) => {
if (val) formData.value = JSON.parse(JSON.stringify(val));
},
{ immediate: true },
);
watch(
() => [$props.url, $props.filter],
async () => {
originalData.value = null;
state.set(modelValue, null);
reset();
await fetch();
}
},
);
onBeforeRouteLeave((to, from, next) => {
@ -197,7 +203,6 @@ async function fetch() {
updateAndEmit('onFetch', data);
} catch (e) {
state.set(modelValue, {});
originalData.value = {};
throw e;
}
}
@ -254,13 +259,12 @@ function filter(value, update, filterOptions) {
(ref) => {
ref.setOptionIndex(-1);
ref.moveOptionSelection(1, true);
}
},
);
}
function updateAndEmit(evt, val, res) {
state.set(modelValue, val);
originalData.value = val && JSON.parse(JSON.stringify(val));
if (!$props.url) arrayData.store.data = val;
emit(evt, state.get(modelValue), res);