Element-UI表单动态添加字段:至少2个必填,支持增删
Hey Nancy, let's work through this problem together—you're super close, just need to tweak how you manage your options data and add some logic for validation and field controls.
1. Why All Inputs Are Syncing (And How to Fix It)
The root issue is that every input is bound to the same single options variable. Instead, you need to store each option as a separate item in an array. Let's start by updating your Vue data to use an array, initialized with two empty values for your required initial fields:
data() { return { optionsList: ['', ''], // Initial 2 required options formRules: { // Validation rules for the first two mandatory options 'optionsList.0': [ { required: true, message: 'Please enter an option', trigger: 'blur' } ], 'optionsList.1': [ { required: true, message: 'Please enter an option', trigger: 'blur' } ] } } }
2. Update the Template for Dynamic Field Rendering
Now rewrite your template to loop through the optionsList array. We'll show the delete button only when there are more than 2 options (to enforce the minimum requirement):
<el-form :model="this" :rules="formRules"> <!-- Header with Add Button --> <el-row> <el-col :span="22"> <h4>Options</h4> </el-col> <el-col :span="2"> <div class="btn-link-plus action-button" @click="addOption"> <i class="fas fa-plus"></i> </div> </el-col> </el-row> <!-- Render each option dynamically --> <el-row v-for="(option, index) in optionsList" :key="index"> <el-col :span="22"> <el-form-item :prop="`optionsList.${index}`"> <el-input v-model="optionsList[index]" placeholder="Enter option content"></el-input> </el-form-item> </el-col> <el-col :span="2" v-if="optionsList.length > 2"> <div class="btn-link-delete action-button" @click="removeOption(index)"> <i class="fas fa-trash-alt"></i> </div> </el-col> </el-row> </el-form>
3. Add Methods for Adding/Removing Options
Add these methods to handle field creation and deletion, with checks to ensure we never drop below 2 options:
methods: { addOption() { this.optionsList.push(''); // Add empty field for new option }, removeOption(index) { // Only allow deletion if we have more than 2 options if (this.optionsList.length > 2) { this.optionsList.splice(index, 1); } else { this.$message.warning('You need at least 2 options'); } } }
4. Key Details for Your Use Case
- Required Field Enforcement: The first two options are marked as required via the
formRules, using dynamic prop indexing to target each array item. - Data Handling: When submitting the form, you can directly pass the
optionsListarray to your backend to store in the separate options table. - User Experience: Users can add as many extra options as needed, but can't delete down to fewer than 2—keeping your requirement intact.
This setup fixes the input sync issue, enforces your validation rules, and gives users the flexibility to manage options as needed.
内容的提问来源于stack exchange,提问作者Nancy

