1. 程式人生 > 其它 >element-ui el-form 某一值為陣列,各項必填驗證

element-ui el-form 某一值為陣列,各項必填驗證

<template>
  <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="80px"
          size="small"
          class="demo-ruleForm"
        >
          <el-form-item label="問題" prop="question">
            <el-input
              
v-model="ruleForm.question" maxlength="30" clearable placeholder="請輸入問題" ></el-input> </el-form-item> <div v-for="(item, index) in ruleForm.items" :key="index"> <el-form-item :label
="'選項' + (index + 1)" :prop="`items[${index}].answer`" :rules="{ required: true, message: '請輸入答案', trigger: 'blur' }" > <el-input v-model="item.answer" maxlength="30" clearable placeholder
="請輸入答案" ></el-input> <el-button v-if="index > 0" type="text" @click="deleteItem(index)" size="small" >刪除</el-button > </el-form-item> </div> <el-form-item label=""> <el-button :disabled="ruleForm.items.length >= 5" type="text" @click="addItem()" size="small" icon="el-icon-plus" >確認新增</el-button > </el-form-item> </el-form> </div> </template> <script> export default { data() { return { ruleForm: { question: "", items: [ { answer: "", }, ], }, rules: { question: [{ required: true, message: "請輸入問題", trigger: "blur" }], }, }; }, created() {}, mounted() {}, methods: { addItem() { if (this.ruleForm.items.length >= 5) return; this.ruleForm.items.push({ answer: "", }); }, deleteItem(index) { this.ruleForm.items.splice(index, 1); }, }, }; </script> <style scoped lang="scss"></style>