Bootstrap

vue3 动态生成表单

vue3 动态生成表单

具体需求就是点击添加按钮,生成一个和上面一样的表单,点击删除删除一个表单,当只有一个表单时不能删除

如图:
在这里插入图片描述
当我接到这个需求的时候,脑子第一映像就是转换成数组的增删array.push(),array.pop().就可以了。

那么直接上代码把

<template>
        <el-row>
          <el-button type="primary" @click="addFeedBackForm">添加</el-button>
          <el-button type="danger" @click="delFeedBackForm">删除</el-button>
        </el-row>
    <template v-for="(item, index) in addForms" :key="index">
      <el-form
        class="addForm"
        label-width="100px"
        :model="item"
      >
        <el-form-item label="反映的问题" label-width="100px" prop="item.feedback">
          <el-input v-model="item.feedback" />
        </el-form-item>
        <el-form-item label="问题描述" label-width="100px" prop="item.describe">
          <el-input v-model="item.describe" />
        </el-form-item>
      </el-form>
    </template>
 
</template>

<script>

export default defineComponent({
  name: 'DynamicsCreateForm',
  setup() {
    const state = reactive({
      addForms: [
        {
          feedback: '',
          describe: '',
        }
      ],
    })

    // 添加问题反馈表单
    const addFeedBackForm = () => {
      const addFormItem = {
          feedback: '',
          describe: '',
      }
      state.addForms.push(addFormItem)
    }

    // 删除问题反馈表单
    const delFeedBackForm = () => {
      if (state.addForms.length === 1) {
        $baseMessage('只有一项不能再删了', 'error', 'vab-hey-message-error')
        return
      }
      state.addForms.pop()
    }


    return {
      ...toRefs(state),
      addFeedBackForm,
      delFeedBackForm,
    }
  },
})
</script>
<style lang="scss" scoped>
.addForm {
  border: 1px solid #d0cdcd;
  border-radius: 5px;
  padding: 20px 30px;
  margin-bottom: 30px;
}
}
</style>
;