element-ui中el-form表单项循环渲染,并添加相关校验
关于这类功能需求,项目中还是挺常见的,所以今天抽空整理一下笔记。
效果图如下:
话不多说,直接上代码(vue3)
<template>
<el-form ref="formRef" :model="formList" :rules="rules" label-width="130px">
<div v-for="(item, index) in formList.list" :key="index">
<el-form-item
:label="`名称${index + 1}`"
:prop="`list[${index}].name`"
:rules="rules.name"
>
<el-input v-model="item.name" placeholder="请输入" />
</el-form-item>
<el-form-item
:label="`时间`"
:prop="`list[${index}].time`"
:rules="rules.time"
>
<el-time-picker
v-model="item.time"
value-format="HH:mm:ss"
placeholder="请选择时间"
>
</el-time-picker>
</el-form-item>
</div>
<el-form-item label="备注" prop="remark">
<el-input
v-model="formList.remark"
maxlength="200"
placeholder="请输入"
:autosize="{ minRows: 2, maxRows: 4 }"
show-word-limit
type="textarea"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">提交</el-button>
</el-form-item>
</el-form>
</template>
<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
const formList = ref({
list: [
{ name: '', time: '' },
{ name: '', time: '' },
],
remark: '',
});
const formRef = ref();
const rules = ref({
name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
time: [{ required: true, message: '请选择时间', trigger: 'change' }],
});
const onSubmit = () => {
formRef.value.validate((valid) => {
if (valid) {
ElMessage.success('提交成功!');
} else {
return false;
}
});
};
</script>
主要注意的点是循环的表单项 prop
和rules
的绑定。
文章来自(https://lifangdan.github.io/blog/views/frontEnd/vue/elForm.html)
网友评论