elment-plus的表单组件的标签有el-form,el-form-item。
单个el-form标签内包裹若干个el-form-item,el-form-item包裹具体的表单组件,如输入框组件,多选组件,日期组件等。
el-form组件的主要作用是:提供统一的布局给其他表单组件,其他组件可以继承表单组件的size,以及规则校验
form表单主要属性如下:
属性名 | 说明 | 默认值 |
---|---|---|
model | 表单数据对象 | — |
rules | 表单验证规则 | — |
inline | 行内表单模式 | false |
label-position | left right label-width | right |
label-width | ‘50px’ auto | ‘’ |
show-message | 是否显示校验错误信息 | true |
inline-message | 是否以行内形式展示校验信息 | false |
status-icon | 是否在输入框中显示校验结果反馈图标 | false |
size | 表单尺寸 |
form-item 主要属性如下:
属性名 | 说明 | 默认值 |
---|---|---|
prop | validate,resetField时使用,一般和v-model值保持一致 | — |
label | 标签文本 | — |
用法示例
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance,FormRules } from 'element-plus'
const formRef = ref<FormInstance>()
interface Good {
goodName:string
stock:number
createDate:Date
description:string
}
const checkStock = (rule: any, value: any, callback: any) => {
console.log("checkStock ",value)
if (!value) {
return callback(new Error('Please input the age'))
}
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error('Please input digits'))
} else {
if (value < 10) {
callback(new Error('stock must be greater than 10'))
} else {
callback()
}
}
}, 1000)
}
const ruleForm=reactive<FormRules<Good>>({
goodName:[
{required:true,
message:"please input goodName",
trigger:'change'
}
],
stock:[
{
validator:checkStock
}
]
})
const goodForm=ref<Good>({
goodName:"",
stock:10,
createDate:new Date(),
description:""
});
const submitForm=()=>{
formRef.value.validate((valid:Boolean)=>{
if (valid){
console.log("submit success ",goodForm) ;
}else{
console.log("form validate error ");
}
})
}
const resetForm=()=>{
formRef.value.resetFields()
}
</script>
<template>
<el-form :model="goodForm" status-icon label-position="left" label-width="auto" ref="formRef" :rules="ruleForm">
<el-form-item label="goodName" prop="goodName">
<el-input v-model="goodForm.goodName" placeholder="please enter goodName"></el-input>
</el-form-item>
<el-form-item label="stock" prop="stock">
<el-input-number v-model="goodForm.stock" :step="1"></el-input-number>
</el-form-item>
<el-form-item label="createDate" prop="createDate">
<el-date-picker type="date" v-model="goodForm.createDate" format="YYYY-MM-DD" clearable></el-date-picker>
</el-form-item>
<el-form-item label="description" prop="description">
<el-input type="textarea" v-model="goodForm.description" placeholder="please enter description"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">submit</el-button>
<el-button @click="resetForm">reset</el-button>
</el-form-item>
</el-form>
</template>
<style scoped>
</style>
https://element-plus.org/zh-CN/component/form.html#form-attributes