create.vue 1.59 KB
<script lang="ts" setup>
  import type { CreateModalDefineExposeType } from '../../../types';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchemas } from './create.config';
  import { NodeData } from '../../../types/node';
  import { CredentialsCard } from './CredentialsCard';
  import { ref, unref } from 'vue';
  import { MqttFieldsEnum } from '../../../enum/formField/external';

  defineProps<{
    config: NodeData;
  }>();

  const credentialsCardElRef = ref<Nullable<InstanceType<typeof CredentialsCard>>>();

  const [register, { validate, getFieldsValue, setFieldsValue, resetFields }] = useForm({
    schemas: formSchemas,
    showActionButtonGroup: false,
  });

  const getValue: CreateModalDefineExposeType['getFieldsValue'] = async () => {
    await validate();
    await unref(credentialsCardElRef)?.validate();
    const value = getFieldsValue() || {};
    const credentialsValue = unref(credentialsCardElRef)?.getFieldsValue();
    return {
      ...value,
      [MqttFieldsEnum.CREDENTIALS]: credentialsValue,
    };
  };

  const setValue: CreateModalDefineExposeType['setFieldsValue'] = (value) => {
    resetFields();
    setFieldsValue(value);
    unref(credentialsCardElRef)?.setFieldsValue(value?.[MqttFieldsEnum.CREDENTIALS]);
  };

  defineExpose({
    setFieldsValue: setValue,
    getFieldsValue: getValue,
  } as CreateModalDefineExposeType);
</script>

<template>
  <BasicForm @register="register">
    <template #credentials="{ field, model }">
      <CredentialsCard ref="credentialsCardElRef" v-model:value="model[field]" />
    </template>
  </BasicForm>
</template>