Formulario ​

El formulario consiste en input, radio, select, checkbox y así sucesivamente. Con el formulario, usted puede recoger, verificar y enviar datos.

TIP

El componente ha sido actualizado con un diseño flex para reemplazar el antiguo diseño flotante.

Formulario básico ​

Incluye todo tipo de entradas, tales como input, select, radio y checkbox.

En cada componente form, necesita un campo form-item que es el contenedor del ítem.

Activity name
Activity zone
please select your zone
Activity time
-
Instant delivery
Activity type
Resources
Activity form

TIP

W3C reglamenta esto

Cuando solo hay un campo de entrada de texto de una sola línea en un formulario, el agente de usuario debe aceptar Enter en ese campo como una solicitud de envío del formulario.. Para evitar este comportamiento, puede añadir @submit.prevent en <el-form>.

Formulario inline ​

Cuando el espacio vertical es limitado y el formulario es relativamente simple, puede ponerlo en una única línea.

Set the inline attribute to true and the form will be inline.

Approved by
Activity zone
Activity zone
Activity time

Alineación ​

Depending on your design, there are several different ways to align your label element.

You can set label-position of el-form-item separately 2.7.7. If the value is empty, the label-position of el-form is used.

The label-position attribute decides how labels align, it can be top or left. When set to top, labels will be placed at the top of the form field.

Form Align
Form Item Align
Name
Activity zone
Activity form

Validación ​

Form component allows you to verify your data, helping you find and correct errors.

Just add the rules attribute for Form component, pass validation rules, and set prop attribute for FormItem as a specific key that needs to be validated. See more information at async-validator.

Activity name
Activity zone
Activity zone
Activity count
Activity count
Activity time
-
Instant delivery
Activity location
Activity type
Resources
Activity form

Reglas personalizadas de validación ​

This example shows how to customize your own validation rules to finish a two-factor password verification.

Here we use status-icon to reflect validation result as an icon.

TIP

Custom validate callback function must be called. See more advanced usage at async-validator.

Añadir/Eliminar validaciones del elemento del formulario ​

In addition to passing all validation rules at once on the form component, you can also pass the validation rules or delete rules on a single form field dynamically.

Email
Domain0

Validación numérica ​

Number Validate need a .number modifier added on the input v-model binding,it's used to transform the string value to the number which is provided by Vue.

age

TIP

When an el-form-item is nested in another el-form-item, its label width will be 0. You can set label-width on that el-form-item if needed.

Control de tamaño ​

All components in a Form inherit their size attribute from that Form. Similarly, FormItem also has a size attribute.

Still you can fine tune each component's size if you don't want that component to inherit its size from From or FormItem.


Activity name
Activity zone
please select your zone
Activity time
-
Activity type
Resources

Accesibilidad ​

When only a single input (or related control such as select or checkbox) is inside of a el-form-item, the form item's label will automatically be attached to that input. However, if multiple inputs are inside of the el-form-item, the form item will be assigned the WAI-ARIA role of group instead. In this case, it is your responsibility to assign assistive labels to the individual inputs.

Full Name
Your Information

API del Formulario ​

Form Attributes ​

NombreDescripciónTipoPor defecto
modelDatos del componente de formulario.object—
rulesReglas de validación.object—
inlineSi el formulario es inline.booleanfalse
label-positionPosición de la etiqueta. Si se establece en 'left' o 'right', se necesita definir la proplabel-width.enumright
label-widthAncho de la etiqueta, ej.: '50px'. Todos los componentes del formulario que sean hijos directos heredaran este valor. se puede usar auto.string / number''
label-suffixSufijo de la etiqueta.string''
hide-required-asteriskSi los campos obligatorios deben tener un asterisco rojo (estrella) al lado de sus etiquetas.booleanfalse
require-asterisk-positionPosición del asterisco.enumleft
show-messageSi mostrar o no el mensaje de error.booleantrue
inline-messageSi mostrar el mensaje de error en línea con el elemento del formulario.booleanfalse
status-iconSi se muestra un icono que indique el resultado de la validación.booleanfalse
validate-on-rule-changeSi se desencadena la validación cuando la prop rules cambia.booleantrue
sizeControla el tamaño de los componentes en este formulario.enum—
disabledDeshabilitar o no todos los componentes en este formulario. Before 2.12.0, if set to true, it will override the disabled prop of the inner component. After 2.12.0, the configuration of the internal components takes precedence.booleanfalse
scroll-to-errorCuando la validación falla, desplácese a la primera entrada del formulario de error.booleanfalse
scroll-into-view-options 2.3.2Cuando la validación falla, se desplaza al primer elemento de error basado en la opción scrollIntoView. scrollIntoView.object / booleantrue

Form Events ​

NameDescripciónTipo
validatetriggers after a form item is validatedFunction

Form Slots ​

NombreDescripciónSubtags
defaultcustomize default contentFormItem

Form Exposes ​

NombreDescripciónTipo
validateValidar todo el formulario. Recibe un callback o devuelve Promise.Function
validateFieldValidar campos específicos.Function
resetFieldsRestablece los campos especificados y elimina el resultado de la validación.Function
scrollToFieldDesplazarse hasta los campos especificados.Function
clearValidateClear validation messages for all or specified fields.Function
fields 2.7.3Get all fields context.array
getField 2.10.2Get a field context.Function
setInitialValues 2.13.1Set initial values for form fields. When resetFields is called, fields will reset to these values.Function

FormItem API ​

FormItem Attributes ​

NombreDescripciónTypeDefault
propA key of model. It could be a path of the property (e.g a.b.0 or ['a', 'b', '0']). In the use of validate and resetFields method, the attribute is required.string / string[]—
labelLabel text.string—
label-position 2.7.7Position of item label. If set to 'left' or 'right', label-width prop is also required. Default extend label-position of form.enum''
label-widthWidth of label, e.g. '50px'. 'auto' is supported.string / number—
requiredWhether the field is required or not, will be determined by validation rules if omitted.boolean—
rulesValidation rules of form, see the following table, more advanced usage at async-validator.object—
errorField error message, set its value and the field will validate error and show this message immediately.string—
show-messageWhether to show the error message.booleantrue
inline-messageInline style validate message.booleanfalse
sizeControl the size of components in this form-item.enum—
forSame as for in native label.string—
validate-statusValidation state of formItem.enum—

Reglas de los componentes del formulario ​

NombreDescripciónTipoPor defecto
triggerHow the validator is triggered.enum—

TIP

If you don't want to trigger the validator based on input events, set the validate-event attribute as false on the corresponding input type components (<el-input>, <el-radio>, <el-select>, ...).

FormItem Slots ​

NombreDescripciónTipo
defaultContent of Form Item.—
labelCustom content to display on label.object
errorCustom content to display validation message.object

FormItem Exposes ​

NombreDescripciónTipo
sizeForm item size.object
validateMessageValidation message.object
validateStateValidation state.object
validateValidate form item.Function
resetFieldReset current field and remove validation result.Function
clearValidateRemove validation status of the field.Function
setInitialValue 2.13.1Set initial value for this field. When resetField is called, the field will reset to this value.Function

Type Declarations ​

Show declarations
ts
type Arrayable<T> = T | T[]

type FormValidationResult = Promise<boolean>

// ValidateFieldsError: see [async-validator](https://github.com/yiminghe/async-validator/blob/master/src/interface.ts)
type FormValidateCallback = (
  isValid: boolean,
  invalidFields?: ValidateFieldsError
) => Promise<void> | void

// RuleItem: see [async-validator](https://github.com/yiminghe/async-validator/blob/master/src/interface.ts)
interface FormItemRule extends RuleItem {
  trigger?: Arrayable<string>
}

type Primitive = null | undefined | string | number | boolean | symbol | bigint
type BrowserNativeObject = Date | FileList | File | Blob | RegExp
type IsTuple<T extends ReadonlyArray<any>> = number extends T['length']
  ? false
  : true
type ArrayMethodKey = keyof any[]
type TupleKey<T extends ReadonlyArray<any>> = Exclude<keyof T, ArrayMethodKey>
type ArrayKey = number
type PathImpl<K extends string | number, V> = V extends
  Primitive | BrowserNativeObject
  ? `${K}`
  : `${K}` | `${K}.${Path<V>}`
type Path<T> =
  T extends ReadonlyArray<infer V>
    ? IsTuple<T> extends true
      ? {
          [K in TupleKey<T>]-?: PathImpl<Exclude<K, symbol>, T[K]>
        }[TupleKey<T>]
      : PathImpl<ArrayKey, V>
    : {
        [K in keyof T]-?: PathImpl<Exclude<K, symbol>, T[K]>
      }[keyof T]
type FieldPath<T> = T extends object ? Path<T> : never
// MaybeRef: see [@vueuse/core](https://github.com/vueuse/vueuse/blob/main/packages/shared/utils/types.ts)
// UnwrapRef: see [vue](https://github.com/vuejs/core/blob/main/packages/reactivity/src/ref.ts)
type FormRules<T extends MaybeRef<Record<string, any> | string> = string> =
  Partial<
    Record<
      UnwrapRef<T> extends string ? UnwrapRef<T> : FieldPath<UnwrapRef<T>>,
      Arrayable<FormItemRule>
    >
  >

type FormItemValidateState = (typeof formItemValidateStates)[number]
type FormItemProps = ExtractPropTypes<typeof formItemProps>

type FormItemContext = FormItemProps & {
  $el: HTMLDivElement | undefined
  size: ComponentSize
  validateMessage: string
  validateState: FormItemValidateState
  isGroup: boolean
  labelId: string
  inputIds: string[]
  hasLabel: boolean
  fieldValue: any
  propString: string
  addInputId: (id: string) => void
  removeInputId: (id: string) => void
  validate: (
    trigger: string,
    callback?: FormValidateCallback
  ) => FormValidationResult
  resetField(): void
  clearValidate(): void
  setInitialValue: (value: any) => void
}

Fuente ​

Componentes • Style • Documentación

Contribuidores ​