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

Vue3 输入指定数字动态添加对应数量输入框的实现问题求助

实现方案

1. 模板部分修改

<DialogTitle as="h3" class="text-xl leading-6 font-medium text-gray-900 py-2">Transaction #1</DialogTitle>
<!-- 数量输入框,type设为number限制输入内容为数字 -->
<input 
  type="number" 
  v-model="inputs.sequence" 
  @input='$emit("update:modelValue", inputs)' 
  class="border border-gray-300 py-2 px-1 text-lg" 
/>
<!-- 遍历动态数组渲染对应数量的输入框 -->
<div v-for="(item, index) in dynamicInputs" :key="index" class="mt-2">
  <input 
    v-model="dynamicInputs[index]" 
    type="text" 
    class="border border-gray-300 py-2 px-1 text-lg" 
    placeholder="动态生成输入框"
  />
</div>

2. 逻辑部分修改

export default {
  name:'prize-editor',
  components: {
    DropImages,
    date,
    DialogTitle
  },
  props:{
    modelValue:Object
  },
  setup(props){
    let inputs = ref({
      detail:'',
      name:'',
      startDate:'',
      sequence:'',
      rewardId:'',
      imageUrl:"",
    })
    // 新增响应式数组存储动态输入框的内容
    const dynamicInputs = ref([])

    onMounted( () => {
      inputs.value=props.modelValue
    });
    watch(props.modelValue, (value) => {
      inputs.value = value
      console.log('watch',value)
    })
    // 监听输入的数量,自动调整输入框个数
    watch(() => inputs.value.sequence, (newVal) => {
      const count = parseInt(newVal) || 0
      if (count > dynamicInputs.value.length) {
        // 数量不足时补充空占位项
        const addCount = count - dynamicInputs.value.length
        for(let i=0; i<addCount; i++){
          dynamicInputs.value.push('')
        }
      } else {
        // 数量超出时截断多余项
        dynamicInputs.value.splice(count)
      }
    }, {immediate: true})

    return{
      inputs,
      dynamicInputs
    }
  },
};

说明

  • dynamicInputs数组专门存储所有动态生成输入框的内容,后续提交数据可以直接取该数组的值
  • 监听inputs.sequence的变化自动同步输入框数量,输入非数字内容时会默认识别为0,清空所有动态输入框
  • 加immediate: true配置,初始化如果有默认数值也能直接渲染对应数量的输入框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:57:03