Skip to content

Form 表单

表单包含 输入框, 单选框, 下拉选择, 多选框 等用户输入的组件。 使用表单,您可以收集、验证和提交数据。

典型表单

最基础的表单包括各种输入表单项,比如input、select、radio、checkbox等。

在每一个 form 组件中,你需要一个 form-item 字段作为输入项的容器,用于获取值与验证值。

form value:

{
  "email": "123",
  "password": "",
  "confirmPwd": ""
}
典型表单
Form 典型表单
<script setup>
import { reactive, ref } from 'vue'
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import Form from '@/components/Form/Form.vue'
import FormItem from '@/components/Form/FormItem.vue'
import Input from '@/components/Input/Input.vue'
import Button from '@/components/Button/Button.vue'
const formRef = ref()
const model = reactive({
  email: '123',
  password: '',
  confirmPwd: ''
})
const rules = {
  email: [{ type: 'email', required: true, trigger: 'blur' }],
  password: [{ type: 'string', required: true, trigger: 'blur', min: 3, max: 5 }],
  confirmPwd: [
    { type: 'string', required: true, trigger: 'blur' },
    {
      validator: (rule, value) => value === model.password,
      trigger: 'blur',
      message: '两个密码必须相同'
    }
  ]
}

const submit = async () => {
  try {
    await formRef.value.validate()
    console.log('passed!')
  } catch (e) {
    console.log('the error', e)
  }
}
const reset = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <div>
    <Form ref="formRef" :model="model" :rules="rules">
      <FormItem label="the email" prop="email">
        <Input v-model="model.email" />
      </FormItem>
      <FormItem label="the password" prop="password">
        <template #label="label">
          <Button type="info">{{ label }}</Button>
        </template>
        <Input v-model="model.password" type="password" />
      </FormItem>
      <FormItem prop="confirmPwd" label="confirm password">
        <Input v-model="model.confirmPwd" type="password" />
      </FormItem>
      <FormItem prop="confirmPwd" label="confirm password">
        <template #default="{ validate }">
          <input v-model="model.confirmPwd" type="password" @blur="validate" />
        </template>
      </FormItem>
      <div :style="{ textAlign: 'center' }">
        <Button type="primary" @click.prevent="submit">Submit</Button>
        <Button @click.prevent="reset">Reset</Button>
      </div>
    </Form>
    <p>form value:</p>

    <pre>{{ model }}</pre>
  </div>
</template>

<style></style>

API

Form Attributes

参数说明类型默认值
model表单数据对象Record<string, any>-
rules校验规则对象Record<string, FormRuleItem[]>-

FormItem Attributes

参数说明类型默认值
label标签文本string-
prop对应 model 字段名,用于校验与重置string-

Form Exposes

方法名说明签名
validate校验整个表单() => Promise<any>
resetFields重置全部字段() => void
clearValidate清除全部校验状态() => void

FormItem Exposes

方法名说明签名
validate校验当前字段(trigger?: string) => Promise<any>
clearValidate清除当前字段校验状态() => void
resetField重置当前字段值与状态() => void