竹一一 2024-04-22 04:31 采纳率: 10.5%
浏览 9

关于读取动态添加的输入框数据

Vue前端建立两个div放入两个表单,需要动态按钮添加输入框或删除,一次添加两个,输入框分别绑定数据模型medicant(两个参数name(名称),left(数量)),equipment(两个参数name(名称),left(数量)),点击提交后将两个div的表单分别返回一个list数组,数组对象为两个数据模型,如何实现?

  • 写回答

6条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-04-22 04:31
    关注

    引自免费微信小程序:皆我百晓生

    在 Vue.js 中,你可以使用 v-for 指令来动态创建输入框,并通过计算属性来处理数据。下面是一个详细的步骤和示例代码来实现这个需求。

    首先,在 HTML 部分,你需要定义两个 div,每个 div 内包含两个输入框,以及添加和删除按钮。这里使用了 Vue 的 v-model 来绑定输入框的数据。

    <div id="app">
      <div>
        <h3>Medicants</h3>
        <div v-for="(medicant, index) in medicants" :key="index">
          <input type="text" v-model="medicant.name" placeholder="Name" />
          <input type="number" v-model="medicant.left" placeholder="Left" />
          <button @click="removeMedicant(index)">Delete</button>
        </div>
        <button @click="addMedicant">Add Medicant</button>
      </div>
    
      <div>
        <h3>Equipment</h3>
        <div v-for="(equipment, index) in equipmentList" :key="index">
          <input type="text" v-model="equipment.name" placeholder="Name" />
          <input type="number" v-model="equipment.left" placeholder="Left" />
          <button @click="removeEquipment(index)">Delete</button>
        </div>
        <button @click="addEquipment">Add Equipment</button>
      </div>
    
      <button @click="submitForm">Submit</button>
      <pre>{{ result }}</pre>
    </div>
    

    然后在 Vue 实例中,定义数据模型和方法。这里我们有两个数据模型 medicantsequipmentList,以及用于保存最终结果的 result。另外还有添加和删除输入框的方法。

    new Vue({
      el: '#app',
      data() {
        return {
          medicants: [{ name: '', left: '' }],
          equipmentList: [{ name: '', left: '' }],
          result: '',
        };
      },
      methods: {
        addMedicant() {
          this.medicants.push({ name: '', left: '' });
        },
        removeMedicant(index) {
          this.medicants.splice(index, 1);
        },
        addEquipment() {
          this.equipmentList.push({ name: '', left: '' });
        },
        removeEquipment(index) {
          this.equipmentList.splice(index, 1);
        },
        submitForm() {
          this.result = {
            medicants: this.medicants,
            equipment: this.equipmentList,
          };
        },
      },
    });
    

    在这个例子中,当你点击 "Add Medicant" 或 "Add Equipment" 按钮时,会动态添加新的输入框。点击 "Delete" 按钮可以移除相应的输入框。最后,点击 "Submit" 按钮会将当前的 medicantsequipmentList 数据模型内容赋值给 result,并在页面上显示出来。

    这是一个基础的实现,实际项目中可能还需要进行一些额外的验证和格式化。如果你想要更复杂的逻辑,例如限制最大输入数量、实时更新提交按钮状态等,可以根据需要扩展这些方法。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 4月22日