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
相关产品推荐
相关产品推荐

