Form 表单

由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据

典型表单

包括各种表单项,比如输入框、选择器、开关、单选框、多选框等。

Form 表单 - 图1

在 Form 组件中,每一个表单域由一个 Form-Item 组件构成,表单域中可以放置各种类型的表单控件,包括 Input、Select、Checkbox、Radio、Switch、DatePicker、TimePicker

  1. <el-form ref="form" :model="form" label-width="80px">
  2. <el-form-item label="活动名称">
  3. <el-input v-model="form.name"></el-input>
  4. </el-form-item>
  5. <el-form-item label="活动区域">
  6. <el-select v-model="form.region" placeholder="请选择活动区域">
  7. <el-option label="区域一" value="shanghai"></el-option>
  8. <el-option label="区域二" value="beijing"></el-option>
  9. </el-select>
  10. </el-form-item>
  11. <el-form-item label="活动时间">
  12. <el-col :span="11">
  13. <el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker>
  14. </el-col>
  15. <el-col class="line" :span="2">-</el-col>
  16. <el-col :span="11">
  17. <el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>
  18. </el-col>
  19. </el-form-item>
  20. <el-form-item label="即时配送">
  21. <el-switch v-model="form.delivery"></el-switch>
  22. </el-form-item>
  23. <el-form-item label="活动性质">
  24. <el-checkbox-group v-model="form.type">
  25. <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
  26. <el-checkbox label="地推活动" name="type"></el-checkbox>
  27. <el-checkbox label="线下主题活动" name="type"></el-checkbox>
  28. <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
  29. </el-checkbox-group>
  30. </el-form-item>
  31. <el-form-item label="特殊资源">
  32. <el-radio-group v-model="form.resource">
  33. <el-radio label="线上品牌商赞助"></el-radio>
  34. <el-radio label="线下场地免费"></el-radio>
  35. </el-radio-group>
  36. </el-form-item>
  37. <el-form-item label="活动形式">
  38. <el-input type="textarea" v-model="form.desc"></el-input>
  39. </el-form-item>
  40. <el-form-item>
  41. <el-button type="primary" @click="onSubmit">立即创建</el-button>
  42. <el-button>取消</el-button>
  43. </el-form-item>
  44. </el-form>
  45. <script>
  46. export default {
  47. data() {
  48. return {
  49. form: {
  50. name: '',
  51. region: '',
  52. date1: '',
  53. date2: '',
  54. delivery: false,
  55. type: [],
  56. resource: '',
  57. desc: ''
  58. }
  59. }
  60. },
  61. methods: {
  62. onSubmit() {
  63. console.log('submit!');
  64. }
  65. }
  66. }
  67. </script>

W3C 标准中有如下规定

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

即:当一个 form 元素中只有一个输入框时,在该输入框中按下回车应提交该表单。如果希望阻止这一默认行为,可以在 <el-form> 标签上添加 @submit.native.prevent

行内表单

当垂直方向空间受限且表单较简单时,可以在一行内放置表单。

Form 表单 - 图2

设置 inline 属性可以让表单域变为行内的表单域

  1. <el-form :inline="true" :model="formInline" class="demo-form-inline">
  2. <el-form-item label="审批人">
  3. <el-input v-model="formInline.user" placeholder="审批人"></el-input>
  4. </el-form-item>
  5. <el-form-item label="活动区域">
  6. <el-select v-model="formInline.region" placeholder="活动区域">
  7. <el-option label="区域一" value="shanghai"></el-option>
  8. <el-option label="区域二" value="beijing"></el-option>
  9. </el-select>
  10. </el-form-item>
  11. <el-form-item>
  12. <el-button type="primary" @click="onSubmit">查询</el-button>
  13. </el-form-item>
  14. </el-form>
  15. <script>
  16. export default {
  17. data() {
  18. return {
  19. formInline: {
  20. user: '',
  21. region: ''
  22. }
  23. }
  24. },
  25. methods: {
  26. onSubmit() {
  27. console.log('submit!');
  28. }
  29. }
  30. }
  31. </script>

对齐方式

根据具体目标和制约因素,选择最佳的标签对齐方式。

Form 表单 - 图3

通过设置 label-position 属性可以改变表单域标签的位置,可选值为 topleft,当设为 top 时标签会置于表单域的顶部

  1. <el-radio-group v-model="labelPosition" size="small">
  2. <el-radio-button label="left">左对齐</el-radio-button>
  3. <el-radio-button label="right">右对齐</el-radio-button>
  4. <el-radio-button label="top">顶部对齐</el-radio-button>
  5. </el-radio-group>
  6. <div style="margin: 20px;"></div>
  7. <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
  8. <el-form-item label="名称">
  9. <el-input v-model="formLabelAlign.name"></el-input>
  10. </el-form-item>
  11. <el-form-item label="活动区域">
  12. <el-input v-model="formLabelAlign.region"></el-input>
  13. </el-form-item>
  14. <el-form-item label="活动形式">
  15. <el-input v-model="formLabelAlign.type"></el-input>
  16. </el-form-item>
  17. </el-form>
  18. <script>
  19. export default {
  20. data() {
  21. return {
  22. labelPosition: 'right',
  23. formLabelAlign: {
  24. name: '',
  25. region: '',
  26. type: ''
  27. }
  28. };
  29. }
  30. }
  31. </script>

表单验证

在防止用户犯错的前提下,尽可能让用户更早地发现并纠正错误。

Form 表单 - 图4

Form 组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,并将 Form-Item 的 prop 属性设置为需校验的字段名即可。校验规则参见 async-validator

  1. <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  2. <el-form-item label="活动名称" prop="name">
  3. <el-input v-model="ruleForm.name"></el-input>
  4. </el-form-item>
  5. <el-form-item label="活动区域" prop="region">
  6. <el-select v-model="ruleForm.region" placeholder="请选择活动区域">
  7. <el-option label="区域一" value="shanghai"></el-option>
  8. <el-option label="区域二" value="beijing"></el-option>
  9. </el-select>
  10. </el-form-item>
  11. <el-form-item label="活动时间" required>
  12. <el-col :span="11">
  13. <el-form-item prop="date1">
  14. <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
  15. </el-form-item>
  16. </el-col>
  17. <el-col class="line" :span="2">-</el-col>
  18. <el-col :span="11">
  19. <el-form-item prop="date2">
  20. <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
  21. </el-form-item>
  22. </el-col>
  23. </el-form-item>
  24. <el-form-item label="即时配送" prop="delivery">
  25. <el-switch v-model="ruleForm.delivery"></el-switch>
  26. </el-form-item>
  27. <el-form-item label="活动性质" prop="type">
  28. <el-checkbox-group v-model="ruleForm.type">
  29. <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
  30. <el-checkbox label="地推活动" name="type"></el-checkbox>
  31. <el-checkbox label="线下主题活动" name="type"></el-checkbox>
  32. <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
  33. </el-checkbox-group>
  34. </el-form-item>
  35. <el-form-item label="特殊资源" prop="resource">
  36. <el-radio-group v-model="ruleForm.resource">
  37. <el-radio label="线上品牌商赞助"></el-radio>
  38. <el-radio label="线下场地免费"></el-radio>
  39. </el-radio-group>
  40. </el-form-item>
  41. <el-form-item label="活动形式" prop="desc">
  42. <el-input type="textarea" v-model="ruleForm.desc"></el-input>
  43. </el-form-item>
  44. <el-form-item>
  45. <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
  46. <el-button @click="resetForm('ruleForm')">重置</el-button>
  47. </el-form-item>
  48. </el-form>
  49. <script>
  50. export default {
  51. data() {
  52. return {
  53. ruleForm: {
  54. name: '',
  55. region: '',
  56. date1: '',
  57. date2: '',
  58. delivery: false,
  59. type: [],
  60. resource: '',
  61. desc: ''
  62. },
  63. rules: {
  64. name: [
  65. { required: true, message: '请输入活动名称', trigger: 'blur' },
  66. { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  67. ],
  68. region: [
  69. { required: true, message: '请选择活动区域', trigger: 'change' }
  70. ],
  71. date1: [
  72. { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
  73. ],
  74. date2: [
  75. { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
  76. ],
  77. type: [
  78. { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
  79. ],
  80. resource: [
  81. { required: true, message: '请选择活动资源', trigger: 'change' }
  82. ],
  83. desc: [
  84. { required: true, message: '请填写活动形式', trigger: 'blur' }
  85. ]
  86. }
  87. };
  88. },
  89. methods: {
  90. submitForm(formName) {
  91. this.$refs[formName].validate((valid) => {
  92. if (valid) {
  93. alert('submit!');
  94. } else {
  95. console.log('error submit!!');
  96. return false;
  97. }
  98. });
  99. },
  100. resetForm(formName) {
  101. this.$refs[formName].resetFields();
  102. }
  103. }
  104. }
  105. </script>

自定义校验规则

这个例子中展示了如何使用自定义验证规则来完成密码的二次验证。

Form 表单 - 图5

本例还使用status-icon属性为输入框添加了表示校验结果的反馈图标。

  1. <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  2. <el-form-item label="密码" prop="pass">
  3. <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
  4. </el-form-item>
  5. <el-form-item label="确认密码" prop="checkPass">
  6. <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
  7. </el-form-item>
  8. <el-form-item label="年龄" prop="age">
  9. <el-input v-model.number="ruleForm.age"></el-input>
  10. </el-form-item>
  11. <el-form-item>
  12. <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
  13. <el-button @click="resetForm('ruleForm')">重置</el-button>
  14. </el-form-item>
  15. </el-form>
  16. <script>
  17. export default {
  18. data() {
  19. var checkAge = (rule, value, callback) => {
  20. if (!value) {
  21. return callback(new Error('年龄不能为空'));
  22. }
  23. setTimeout(() => {
  24. if (!Number.isInteger(value)) {
  25. callback(new Error('请输入数字值'));
  26. } else {
  27. if (value < 18) {
  28. callback(new Error('必须年满18岁'));
  29. } else {
  30. callback();
  31. }
  32. }
  33. }, 1000);
  34. };
  35. var validatePass = (rule, value, callback) => {
  36. if (value === '') {
  37. callback(new Error('请输入密码'));
  38. } else {
  39. if (this.ruleForm.checkPass !== '') {
  40. this.$refs.ruleForm.validateField('checkPass');
  41. }
  42. callback();
  43. }
  44. };
  45. var validatePass2 = (rule, value, callback) => {
  46. if (value === '') {
  47. callback(new Error('请再次输入密码'));
  48. } else if (value !== this.ruleForm.pass) {
  49. callback(new Error('两次输入密码不一致!'));
  50. } else {
  51. callback();
  52. }
  53. };
  54. return {
  55. ruleForm: {
  56. pass: '',
  57. checkPass: '',
  58. age: ''
  59. },
  60. rules: {
  61. pass: [
  62. { validator: validatePass, trigger: 'blur' }
  63. ],
  64. checkPass: [
  65. { validator: validatePass2, trigger: 'blur' }
  66. ],
  67. age: [
  68. { validator: checkAge, trigger: 'blur' }
  69. ]
  70. }
  71. };
  72. },
  73. methods: {
  74. submitForm(formName) {
  75. this.$refs[formName].validate((valid) => {
  76. if (valid) {
  77. alert('submit!');
  78. } else {
  79. console.log('error submit!!');
  80. return false;
  81. }
  82. });
  83. },
  84. resetForm(formName) {
  85. this.$refs[formName].resetFields();
  86. }
  87. }
  88. }
  89. </script>

自定义校验 callback 必须被调用。 更多高级用法可参考 async-validator

动态增减表单项

Form 表单 - 图6

除了在 Form 组件上一次性传递所有的验证规则外还可以在单个的表单域上传递属性的验证规则

  1. <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
  2. <el-form-item
  3. prop="email"
  4. label="邮箱"
  5. :rules="[
  6. { required: true, message: '请输入邮箱地址', trigger: 'blur' },
  7. { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  8. ]"
  9. >
  10. <el-input v-model="dynamicValidateForm.email"></el-input>
  11. </el-form-item>
  12. <el-form-item
  13. v-for="(domain, index) in dynamicValidateForm.domains"
  14. :label="'域名' + index"
  15. :key="domain.key"
  16. :prop="'domains.' + index + '.value'"
  17. :rules="{
  18. required: true, message: '域名不能为空', trigger: 'blur'
  19. }"
  20. >
  21. <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>
  22. </el-form-item>
  23. <el-form-item>
  24. <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
  25. <el-button @click="addDomain">新增域名</el-button>
  26. <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
  27. </el-form-item>
  28. </el-form>
  29. <script>
  30. export default {
  31. data() {
  32. return {
  33. dynamicValidateForm: {
  34. domains: [{
  35. value: ''
  36. }],
  37. email: ''
  38. }
  39. };
  40. },
  41. methods: {
  42. submitForm(formName) {
  43. this.$refs[formName].validate((valid) => {
  44. if (valid) {
  45. alert('submit!');
  46. } else {
  47. console.log('error submit!!');
  48. return false;
  49. }
  50. });
  51. },
  52. resetForm(formName) {
  53. this.$refs[formName].resetFields();
  54. },
  55. removeDomain(item) {
  56. var index = this.dynamicValidateForm.domains.indexOf(item)
  57. if (index !== -1) {
  58. this.dynamicValidateForm.domains.splice(index, 1)
  59. }
  60. },
  61. addDomain() {
  62. this.dynamicValidateForm.domains.push({
  63. value: '',
  64. key: Date.now()
  65. });
  66. }
  67. }
  68. }
  69. </script>

数字类型验证

Form 表单 - 图7

数字类型的验证需要在 v-model 处加上 .number 的修饰符,这是 Vue 自身提供的用于将绑定值转化为 number 类型的修饰符。

  1. <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
  2. <el-form-item
  3. label="年龄"
  4. prop="age"
  5. :rules="[
  6. { required: true, message: '年龄不能为空'},
  7. { type: 'number', message: '年龄必须为数字值'}
  8. ]"
  9. >
  10. <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  11. </el-form-item>
  12. <el-form-item>
  13. <el-button type="primary" @click="submitForm('numberValidateForm')">提交</el-button>
  14. <el-button @click="resetForm('numberValidateForm')">重置</el-button>
  15. </el-form-item>
  16. </el-form>
  17. <script>
  18. export default {
  19. data() {
  20. return {
  21. numberValidateForm: {
  22. age: ''
  23. }
  24. };
  25. },
  26. methods: {
  27. submitForm(formName) {
  28. this.$refs[formName].validate((valid) => {
  29. if (valid) {
  30. alert('submit!');
  31. } else {
  32. console.log('error submit!!');
  33. return false;
  34. }
  35. });
  36. },
  37. resetForm(formName) {
  38. this.$refs[formName].resetFields();
  39. }
  40. }
  41. }
  42. </script>

嵌套在 el-form-item 中的 el-form-item 标签宽度默认为零,不会继承 el-formlabel-width。如果需要可以为其单独设置 label-width 属性。

表单内组件尺寸控制

通过设置 Form 上的 size 属性可以使该表单内所有可调节大小的组件继承该尺寸。Form-Item 也具有该属性。

Form 表单 - 图8

如果希望某个表单项或某个表单组件的尺寸不同于 Form 上的size属性,直接为这个表单项或表单组件设置自己的size即可。

  1. <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
  2. <el-form-item label="活动名称">
  3. <el-input v-model="sizeForm.name"></el-input>
  4. </el-form-item>
  5. <el-form-item label="活动区域">
  6. <el-select v-model="sizeForm.region" placeholder="请选择活动区域">
  7. <el-option label="区域一" value="shanghai"></el-option>
  8. <el-option label="区域二" value="beijing"></el-option>
  9. </el-select>
  10. </el-form-item>
  11. <el-form-item label="活动时间">
  12. <el-col :span="11">
  13. <el-date-picker type="date" placeholder="选择日期" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker>
  14. </el-col>
  15. <el-col class="line" :span="2">-</el-col>
  16. <el-col :span="11">
  17. <el-time-picker placeholder="选择时间" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker>
  18. </el-col>
  19. </el-form-item>
  20. <el-form-item label="活动性质">
  21. <el-checkbox-group v-model="sizeForm.type">
  22. <el-checkbox-button label="美食/餐厅线上活动" name="type"></el-checkbox-button>
  23. <el-checkbox-button label="地推活动" name="type"></el-checkbox-button>
  24. <el-checkbox-button label="线下主题活动" name="type"></el-checkbox-button>
  25. </el-checkbox-group>
  26. </el-form-item>
  27. <el-form-item label="特殊资源">
  28. <el-radio-group v-model="sizeForm.resource" size="medium">
  29. <el-radio border label="线上品牌商赞助"></el-radio>
  30. <el-radio border label="线下场地免费"></el-radio>
  31. </el-radio-group>
  32. </el-form-item>
  33. <el-form-item size="large">
  34. <el-button type="primary" @click="onSubmit">立即创建</el-button>
  35. <el-button>取消</el-button>
  36. </el-form-item>
  37. </el-form>
  38. <script>
  39. export default {
  40. data() {
  41. return {
  42. sizeForm: {
  43. name: '',
  44. region: '',
  45. date1: '',
  46. date2: '',
  47. delivery: false,
  48. type: [],
  49. resource: '',
  50. desc: ''
  51. }
  52. };
  53. },
  54. methods: {
  55. onSubmit() {
  56. console.log('submit!');
  57. }
  58. }
  59. };
  60. </script>

Form Attributes

参数说明类型可选值默认值
model表单数据对象object
rules表单验证规则object
inline行内表单模式booleanfalse
label-position表单域标签的位置,如果值为 left 或者 right 时,则需要设置 label-widthstringright/left/topright
label-width表单域标签的宽度,例如 '50px'。作为 Form 直接子元素的 form-item 会继承该值。支持 autostring
label-suffix表单域标签的后缀string
hide-required-asterisk是否显示必填字段的标签旁边的红色星号booleanfalse
show-message是否显示校验错误信息booleantrue
inline-message是否以行内形式展示校验信息booleanfalse
status-icon是否在输入框中显示校验结果反馈图标booleanfalse
validate-on-rule-change是否在 rules 属性改变后立即触发一次验证booleantrue
size用于控制该表单内组件的尺寸stringmedium / small / mini
disabled是否禁用该表单内的所有组件。若设置为 true,则表单内组件上的 disabled 属性不再生效booleanfalse

Form Methods

方法名说明参数
validate对整个表单进行校验的方法,参数为一个回调函数。该回调函数会在校验结束后被调用,并传入两个参数:是否校验成功和未通过校验的字段。若不传入回调函数,则会返回一个 promiseFunction(callback: Function(boolean, object))
validateField对部分表单字段进行校验的方法Function(props: array | string, callback: Function(errorMessage: string))
resetFields对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
clearValidate移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果Function(props: array | string)

Form Events

事件名称说明回调参数
validate任一表单项被校验后触发被校验的表单项 prop 值,校验是否通过,错误消息(如果存在)

Form-Item Attributes

参数说明类型可选值默认值
prop表单域 model 字段,在使用 validate、resetFields 方法的情况下,该属性是必填的string传入 Form 组件的 model 中的字段
label标签文本string
label-width表单域标签的的宽度,例如 '50px'。支持 autostring
required是否必填,如不设置,则会根据校验规则自动生成booleanfalse
rules表单验证规则object
error表单域验证错误信息, 设置该值会使表单验证状态变为error,并显示该错误信息string
show-message是否显示校验错误信息booleantrue
inline-message以行内形式展示校验信息booleanfalse
size用于控制该表单域下组件的尺寸stringmedium / small / mini-

Form-Item Slot

name说明
Form Item 的内容
label标签文本的内容

Form-Item Scoped Slot

name说明
error自定义表单校验信息的显示方式,参数为 { error }

Form-Item Methods

方法名说明参数
resetField对该表单项进行重置,将其值重置为初始值并移除校验结果-
clearValidate移除该表单项的校验结果-