vue elementUI form组件动态添加el-form-item并且动态添加rules必填项校验方法_el-form-item 必填项校验
<template>
<el-form :model="dynamicForm" :rules="rules" ref="dynamicForm" label-width="100px">
<el-form-item
v-for="(item, index) in dynamicForm.items"
:label="'Item ' + item.index"
:key="item.id"
:prop="'items.' + index + '.value'"
:rules="{ required: true, message: 'This field is required', trigger: 'blur' }"
>
<el-input v-model="item.value"></el-input>
<el-button @click.prevent="removeItem(item)">Delete</el-button>
</el-form-item>
<el-button @click="addItem">New Item</el-button>
<el-button type="primary" @click="submitForm">Submit</el-button>
</el-form>
</template>
<script>
export default {
data() {
return {
dynamicForm: {
items: []
},
rules: {}
};
},
methods: {
addItem() {
this.dynamicForm.items.push({
id: Date.now(),
index: this.dynamicForm.items.length + 1,
value: ''
});
},
removeItem(item) {
const index = this.dynamicForm.items.indexOf(item);
if (index !== -1) {
this.dynamicForm.items.splice(index, 1);
}
},
submitForm() {
this.$refs.dynamicForm.validate((valid) => {
if (valid) {
alert('Form is valid!');
} else {
console.log('Form is invalid');
return false;
}
});
}
}
};
</script>
这个代码示例展示了如何在Vue.js中使用Element UI的el-form
组件动态添加和删除表单项,并对这些项进行必填验证。通过为每个表单项指定一个唯一的prop
属性,并在data
中定义对应的rules
对象,我们可以动态地为表单项添加验证规则。这样,每当我们添加新的表单项时,都会自动附加必填的验证规则。
评论已关闭