primevue-mirror/apps/showcase/doc/forms/dynamic/DynamicForm.vue

47 lines
1.6 KiB
Vue
Raw Normal View History

2024-10-23 04:05:27 +00:00
<template>
<Form v-slot="$form" :initialValues :resolver @submit="$emit('submit', $event)" class="flex flex-col gap-4 w-full sm:w-56">
<slot v-bind="$form">
<template v-for="({ groupId, label, messages, ...rest }, name) in fields" :key="name">
<DynamicFormField :groupId :name>
<DynamicFormLabel>{{ label }}</DynamicFormLabel>
<DynamicFormControl v-bind="rest" />
<DynamicFormMessage v-for="(message, index) in messages || [{}]" :key="index" v-bind="message" />
</DynamicFormField>
</template>
<DynamicFormSubmit />
</slot>
</Form>
</template>
2024-10-23 21:57:52 +00:00
<script setup>
2024-10-23 04:05:27 +00:00
import { isNotEmpty } from '@primeuix/utils';
import { zodResolver } from '@primevue/form/resolvers';
import { z } from 'zod';
import DynamicFormControl from './DynamicFormControl.vue';
import DynamicFormField from './DynamicFormField.vue';
import DynamicFormLabel from './DynamicFormLabel.vue';
import DynamicFormMessage from './DynamicFormMessage.vue';
import DynamicFormSubmit from './DynamicFormSubmit.vue';
2024-10-23 21:57:52 +00:00
const props = defineProps({
fields: Object
});
const emit = defineEmits(['submit']);
const defaultValues = ref({});
const schemas = ref({});
const resolver = computed(() => (isNotEmpty(schemas.value) ? zodResolver(z.object(schemas.value)) : undefined));
const initialValues = computed(() => defaultValues.value);
const addField = (name, schema, defaultValue) => {
schema && (schemas.value[name] = schema);
defaultValues.value[name] = defaultValue;
2024-10-23 04:05:27 +00:00
};
2024-10-23 21:57:52 +00:00
provide('$fcDynamicForm', {
addField
});
2024-10-23 04:05:27 +00:00
</script>