BasicForm.vue 2.45 KB
<script lang="ts" setup>
import { NForm, NGrid } from 'naive-ui';
import { computed, reactive, ref, unref, useAttrs } from 'vue';
import { BasicFormProps, FormSchema } from './types/form';
import { basicProps } from './props';
import { useDesign } from '@/hooks/external/useDesign';
import { dateItemType } from './helper';
import { dateUtil } from '@/utils/external/dateUtil';
import { Dayjs } from 'dayjs';
import FormItem from './components/FormItem.vue';
import { deepMerge } from '@/utils/external';

const props = defineProps(basicProps)

const attrs = useAttrs()

const fromModel = reactive<Recordable>({})

const defaultValueRef = ref<Recordable>({})

const isInitialDefaultRef = ref(false)

const propsRef = ref<Partial<BasicFormProps>>({})

const schemaRef = ref<Nullable<FormSchema[]>>(null)

const formElRef = ref<Nullable<Recordable>>(null)

const { prefixCls } = useDesign('basic-form')

const getProps = computed(() => {
  return { ...props, ...unref(propsRef) } as BasicFormProps
})


const getBindValue = computed(() => {
  return { ...attrs, ...unref(getProps) } as Recordable
})


const getSchema = computed(() => {
  const schemas = unref(schemaRef) || unref(getProps).schemas

  for (const schema of schemas) {
    const { defaultValue, component } = schema

    if (defaultValue && dateItemType.includes(component)) {
      if (!Array.isArray(defaultValue)) {
        schema.defaultValue = dateUtil(defaultValue)
      } else {
        const def: Dayjs[] = []
        defaultValue.forEach(item => def.push(dateUtil(item)))
        schema.defaultValue = def
      }
    }
  }

  return schemas
})

async function setProps(params: Partial<BasicFormProps>) {
  propsRef.value = deepMerge(unref(propsRef) || {},)
}

const setFormModel = (key: string, value: any) => {
  fromModel[key] = value

}

const handleEnterPress = () => {

}


</script>

<template>
  <NForm ref="formElRef" :model="fromModel" @keypress.enter="handleEnterPress">
    <NGrid>
      <slot name="formHeader" />
      <template v-for="schema in getSchema" :key="schema.field">
        <FormItem :schema="schema" :formProps="getProps" :allDefaultValues="defaultValueRef" :formModel="fromModel"
          :setFormModel="setFormModel">
          <template #[item]="data" v-for="item in Object.keys($slots)">
            <slot :name="item" v-bind="data" />
          </template>
        </FormItem>
      </template>
      <slot name="formFooter" />
    </NGrid>
  </NForm>
</template>

<style scoped lang="scss">
</style>