﻿# nf-form {#form}

An Element Plus Form wrapper preserving validation and field APIs with expandable query fields.

Import the components below; see the package README for standalone installation.

## Expand and collapse form fields {#example-1}

### Expand and collapse form fields
```vue
<script setup lang="ts">
import { NfForm, NfFormItem } from '@94ai-plus/common-ui'
import { ElInput, ElSelect, ElOption, ElDatePicker, ElSwitch, ElCheckboxGroup, ElCheckbox, ElRadioGroup, ElRadio, ElButton } from 'element-plus'
const ruleForm = ref()
const result = ref('')

import { ref } from 'vue'

const inline = ref(true)
const columns = ref(4)
const labelPosition = ref('top')
const changeLabelPosition = (val) => {
  labelPosition.value = val
}

const form = ref({
  name: '',
  region: '',
  date: '',
  delivery: false,
  type: [],
  resource: '',
  desc: ''
})

const rules = ref({
  name: [
    { required: true, message: 'Please enter event name', trigger: 'blur' },
    { min: 3, max: 5, message: 'The length is 3 Arrive 5 characters', trigger: 'blur' }
  ],
  region: [
    { required: true, message: 'Please select activity area', trigger: 'change' }
  ],
  date: [
    { type: 'date', required: true, message: 'Please select a date', trigger: 'change' }
  ],
  type: [
    { type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' }
  ],
  resource: [
    { required: true, message: 'Please select activity resources', trigger: 'change' }
  ],
  desc: [
    { required: true, message: 'Please fill in the activity form', trigger: 'blur' }
  ]
})

const submitForm = (formName) => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      result.value = 'Submission successful'
    } else {
      result.value = 'Verification failed'
      return false;
    }
  });
}
const resetForm = (formName) => {
  ruleForm.value.resetFields();
}
</script>

<template>
<div class="form-examples">
  <div>
    <nf-form
      :model="form"
      :rules="rules"
      ref="ruleForm"

      :inline='inline'
      :columns='columns'
      :label-position='labelPosition'
      label-width='80px'
    >
      <nf-form-item label="Name" prop="name">
        <el-input v-model="form.name"></el-input>
      </nf-form-item>
      <nf-form-item label="Activity area" prop="region">
        <el-select v-model="form.region" placeholder="Please select activity area">
          <el-option label="Area one" value="shanghai"></el-option>
          <el-option label="Area 2" value="beijing"></el-option>
        </el-select>
      </nf-form-item>
      <nf-form-item label="time" prop="date">
         <el-date-picker type="date" placeholder="Select date" v-model="form.date" style="width: 100%;"></el-date-picker>
      </nf-form-item>
      <nf-form-item label="Instant delivery" prop="delivery">
        <el-switch v-model="form.delivery"></el-switch>
      </nf-form-item>
      <nf-form-item label="Delivery" prop="type">
        <el-checkbox-group v-model="form.type">
          <el-checkbox value="Food/Restaurant online events" name="type">Food/Restaurant online events</el-checkbox>
          <el-checkbox value="Local promotion activities" name="type">Local promotion activities</el-checkbox>
          <el-checkbox value="Offline theme activities" name="type">Offline theme activities</el-checkbox>
          <el-checkbox value="Pure brand exposure" name="type">Pure brand exposure</el-checkbox>
        </el-checkbox-group>
      </nf-form-item>
      <nf-form-item label="special resources" prop="resource">
        <el-radio-group v-model="form.resource">
          <el-radio value="Online brand sponsorship">Online brand sponsorship</el-radio>
          <el-radio value="Offline venues are free">Offline venues are free</el-radio>
        </el-radio-group>
      </nf-form-item>
      <nf-form-item label="form" prop="desc">
        <el-input type="textarea" v-model="form.desc"></el-input>
      </nf-form-item>
      <nf-form-item>
        <el-button @click='inline=!inline'>switch{{ !inline ? 'Inside the industry' : 'block level' }}</el-button>
        <el-button @click='columns++'>Increase the number of folds</el-button>
        <el-button @click='columns = Math.max(1, columns - 1)'>Reduce the number of folds</el-button>
        <el-button @click='changeLabelPosition("top")'>Form item prefix upwards</el-button>
        <el-button @click='changeLabelPosition("right")'>Form item prefix to the right</el-button>
        <el-button @click='changeLabelPosition("left")'>Form item prefix left</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">form validation</el-button>
        <el-button @click="resetForm('ruleForm')">reset checksum</el-button>
      </nf-form-item>
    </nf-form>
  </div>

<output>{{ result }}</output></div>
</template>

<style scoped>
.form-examples {max-width:100%} .form-examples :deep(.el-form-item__content) {flex-wrap:wrap;gap:8px} .form-examples :deep(.el-select) {width:200px;max-width:100%}
</style>
```

## Dynamic form fields {#example-2}

### Dynamic form fields
```vue
<script setup lang="ts">
import { NfForm, NfFormItem } from '@94ai-plus/common-ui'
import { ElInput, ElButton } from 'element-plus'
const validateForm = ref()
const result = ref('')
import { ref } from 'vue'

const dynamicColumns = ref(4)
const dynamicValidateForm = ref({
  domains: [{
    value: '', key: 0
  }],
  email: ''
})

const submitForm = (formName) => {
  validateForm.value.validate((valid) => {
    if (valid) {
      result.value = 'Submission successful'
    } else {
      result.value = 'Verification failed'
      return false;
    }
  });
}
const resetForm = (formName) => {
  validateForm.value.resetFields();
}
const removeDomain = (item) => {
  var index = dynamicValidateForm.value.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.value.domains.splice(index, 1)
  }
}
let domainKey = 0
const addDomain = () => {
  dynamicValidateForm.value.domains.push({
    value: '',
    key: ++domainKey
  });
}
</script>

<template>
<div class="form-examples">
 <nf-form
    :model="dynamicValidateForm"
    ref="validateForm"
    label-width="100px"
    :columns='dynamicColumns'
  >
  <nf-form-item
    prop="email"
    label="Email"
    :rules="[
      { required: true, message: 'Please enter email address', trigger: 'blur' },
      { type: 'email', message: 'Please enter a correct email address', trigger: ['blur', 'change'] }
    ]"
  >
    <el-input v-model="dynamicValidateForm.email" style='width: 200px'></el-input>
  </nf-form-item>
  <nf-form-item
    v-for="(domain, index) in dynamicValidateForm.domains"
    :label="'domain name' + index"
    :key="domain.key"
    :prop="'domains.' + index + '.value'"
    :rules="{
      required: true, message: 'Domain name cannot be empty', trigger: 'blur'
    }"
  >
    <el-input v-model="domain.value" style='width: 200px'></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
  </nf-form-item>
  <nf-form-item>
    <template #label><div  style="opacity: 0;">.</div></template>
    <el-button type="primary" @click="submitForm('validateForm')">Submit</el-button>
    <el-button @click="resetForm('validateForm')">reset</el-button>
    <el-button @click="addDomain">Add domain name</el-button>
    <el-button @click='dynamicColumns++'>Increase the number of folds</el-button>
    <el-button @click='dynamicColumns = Math.max(1, dynamicColumns - 1)'>Reduce the number of folds</el-button>
  </nf-form-item>
</nf-form>

<output>{{ result }}</output></div>
</template>

<style scoped>
.form-examples {max-width:100%} .form-examples :deep(.el-form-item__content) {flex-wrap:wrap;gap:8px} .form-examples :deep(.el-select) {width:200px;max-width:100%}
</style>
```

## Attribute {#props}

| parameters | Description | Type | Optional value | Default value |
| --- | --- | --- | --- | --- |
| model | form data object | object | — | — |
| rules | form validation rules | object | — | — |
| inline | Inline form mode | boolean | — | false |
| label-position | The position of the form field label. If the value is left or right, label-width needs to be set. | string | right/left/top | right |
| label-width | The width of the form field label, for example '50px'. Form-item elements that are direct children of Form inherit this value. Support auto. | string | — | — |
| label-suffix | Suffix for form field labels | string | — | — |
| hide-required-asterisk | Whether to hide the red asterisk next to the label of a required field | boolean | — | false |
| show-message | Whether to display verification error information | boolean | — | true |
| inline-message | Whether to display verification information inline | boolean | — | false |
| status-icon | Whether to display the verification result feedback icon in the input box | boolean | — | false |
| validate-on-rule-change | Whether to trigger a verification immediately after the rules attribute changes | boolean | — | true |
| size | Control the size of components in the form; compatible with mini→small, medium→default. | string | medium/small/mini | undefined |
| disabled | Whether to disable all components within this form. If set to true, the disabled attribute on components within the form will no longer take effect. | boolean | — | false |
| showBtn | Whether to enable the fold button function | boolean | — | true |
| columns | Fold when exceeding the specified number; retain the first columns-1 participants and the last operation item when folding. | number | — | 3 |
| upIcon | Collapse button icon class name; defaults to built-in SVG. | string | — | 'icon-xiangshang2' |
| downIcon | Expand button icon class name; uses built-in SVG by default. | string | — | 'icon-xiangxia2' |
| isCollapse | Initialize whether to fold | boolean | — | true |
| expandBtnType | Expand button type | string | primary/success/warning/danger/info/text/default | '' |
| expandBtnIcon | Expand button icon | string | — | undefined |
| expandBtnPlain | Expand button plain | boolean | — | true |
| expandBtnSize | Expand button size, the default is based on the form size. It is worth noting that after setting this, if it is not a value in the enumeration, it will be regarded as the default size of the button (the default maximum size, equivalent to large) | string | medium/small/mini | undefined |
| expandBtnRound | Expand button round | boolean | — | false |
| expandBtnCircle | Expand buttoncircle | boolean | — | false |
| expandBtnLoading | Expand button loading | boolean | — | false |
| expandBtnDisabled | Expand buttondisabled | boolean | — | false |
| expandBtnTooltipDesc | Expand button tooltip text. | string | — | Follow language pack |
| shrinkBtnTooltipDesc | Collapse button text. | string | — | Follow language pack |

## Methods {#methods}

| method name | Description | parameters |
| --- | --- | --- |
| validate | A method for validating the entire form. The parameter is a callback function. This callback function will be called after the verification is completed, and two parameters will be passed in: whether the verification was successful and the fields that failed the verification. If no callback function is passed in, a promise will be returned | Function(callback: Function(boolean, object)) |
| validateField | How to verify some form fields | Function(props: array |
| resetFields | Reset the entire form, reset all field values to their initial values and remove validation results | — |
| clearValidate | Remove the validation results from the form item. Pass in the prop attribute or array of props of the form item to be removed. If not passed, the verification result of the entire form will be removed. | Function(props: array |
| scrollToField(prop) | Scroll to the specified field. | string |
| getField(prop) | Get field context. | string |
| getFormItems() | Refresh dynamic form item order. | — |

## Event {#events}

| event name | Description | callback parameters |
| --- | --- | --- |
| validate | Triggered after any form item is verified | The form item being validated prop Value, whether the verification passed, error message (if present) |
| isCollapseChange | Triggered by change of form expansion state, true means expansion. | expanded: boolean |

## Slot {#slots}

| Name | Description |
| --- | --- |
| default | Form content; use NfFormItem to register the collapse item. |

## nf-form-item Attribute {#form-item-props}

| parameters | Description | Type | Optional value | Default value |
| --- | --- | --- | --- | --- |
| hidden | Controls whether the form item participates in the hidden drop-down function, true does not participate | boolean | — | false |
| prop | Form field model field, this attribute is required when using the validate and resetFields methods. | string | incoming Form component model fields in | — |
| label | label text | string | — | — |
| label-width | The width of the form field label, for example '50px'. 'auto' is supported. | string | — | — |
| required | Is it required? If not set, it will be automatically generated based on the verification rules. | boolean | — | false |
| rules | form validation rule | object | — | — |
| error | Form field validation error message. Setting this value will change the form validation status to error and display the error message. | string | — | — |
| show-message | Whether to display verification error information | boolean | — | true |
| inline-message | Display verification information inline | boolean | — | false |
| size | Used to control the size of components under this form field | string | medium/small/mini | - |

## nf-form-item Slot {#form-item-slots}

| Name | Description |
| --- | --- |
| default | Contents of Form Item |
| label | The content of the label text |

## nf-form-item Scoped Slot {#form-item-scoped-slots}

| Name | Description |
| --- | --- |
| error | Customize the display mode of form verification information, the parameter is { error } |

## nf-form-item Methods {#form-item-methods}

| method name | Description | parameters |
| --- | --- | --- |
| resetField | Reset the form item, reset its value to its initial value and remove the verification result | - |
| clearValidate | Remove the verification result of this form item | - |

## Instructions for use {#configuration-notes}

The hidden of NfFormItem means that it does not participate in folding and remains on the page. Validation, reset, and field methods use Element Plus's public API; do not rely on Vue 2 private instances.
