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

Vue.js中点击添加按钮动态新增图片上传框的实现咨询

实现思路

你当前的图片上传框是通过遍历defaultData数组动态渲染的,所以实现新增上传框的核心逻辑就是:

  • 将defaultData改为Vue组件的响应式数据(不能定义为组件外部的常量)
  • 点击新增按钮时,往defaultData数组中推入符合格式的新元素,Vue会自动渲染对应的新上传框

完整修正代码

<template>
<b-row>
  <b-col md="3" v-for="item in defaultData" :key="item.key">
    <b-form-group>
        <b-form-file
          accept="image/*"
          placeholder="Choose popup invalid image..."
          drop-placeholder="Drop file here..."
          :name="item.keyName"
        />
    </b-form-group>
  </b-col>
  <b-col md="2">
    <a-button type="button" class="mr-2" html-type="button" @click="addimg" ><i class="fa fa-plus" aria-hidden="true"></i></a-button>
  </b-col>
</b-row>
</template>
<script>
export default {
  data() {
    return {
      defaultData: [
        {
          keyName: 'product-a2', // 注意字符串要加引号,否则会被识别为变量报错
          key: 1
        }
      ]
    }
  },
  methods: {
    addimg() {
      // 生成唯一key,用时间戳即可保证不重复
      const newKey = Date.now()
      this.defaultData.push({
        keyName: `product-${newKey}`, // 可按你的业务需求修改命名规则
        key: newKey
      })
    }
  }
}
</script>

注意事项

  • 原代码中按钮的html-type="submit"如果放在form表单内会触发默认提交行为导致页面刷新,不需要的话改为html-type="button"即可
  • 后续要收集所有上传的文件时,直接遍历defaultData的keyName对应取表单字段值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:57:00