You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue动态表单如何收集多输入值为单个键值对对象

问题根因

输入框无法连续输入的bug出在自定义BaseInput组件的v-model绑定逻辑错误:

  • 父组件循环渲染时,通过v-model="userInput[input.name]"传给子组件的modelValue是单个输入项对应的字符串值,不是整个userInput对象
  • 子组件错误地给原生input绑定了:value="modelValue[name]",相当于在字符串值上取name属性,结果永远是undefined
  • 每次输入第一个字符触发更新后,输入框的值会被重置为undefined,导致无法连续输入,仅能录入单个字符
修复步骤

1. 修改BaseInput组件

子组件直接使用传入的modelValue作为输入框的值即可,不需要额外取属性,修复后代码:

<template>
  <input
    :type="type"
    :name="name"
    :placeholder="placeholder"
    @input="$emit('update:modelValue', $event.target.value)"
    :value="modelValue"
  />
</template>

<script>
export default {
  emits: ["update:modelValue"],
  props: {
    label: {
      type: String,
      required: false,
    },
    placeholder: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: false,
    },
    modelValue: {
      type: String,
      default: ""
    },
  },
};
</script>

2. 父组件无需额外修改

你当前父组件的写法已经满足「收集name为键、输入内容为值的表单对象」的要求:

  • 提前初始化的userInput对象,键名和所有输入项的name属性一一对应
  • 循环渲染时通过v-model直接把每个输入框和userInput的对应键做双向绑定
  • 提交时直接读取this.userInput就能得到符合预期结构的键值对对象,不需要额外遍历DOM或组件收集值
修复后效果
  • 输入框可正常连续输入内容,不会出现输入单个字符就重置的问题
  • 点击提交按钮后,控制台输出的userInput结构完全匹配预期:
{
  name: "user name",
  phone: "1111",
  email: "test@test.com",
  location: "World",
  address: "",
  comment: "no",
}

内容的提问来源于stack exchange,提问作者qweezz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 23:27:35