用vue上传多个动态文件

时间:2020-09-10 04:04:01

标签: javascript vue.js

我知道这个问题已经问了很多,但是其中大多数是如何上传多张图像而又不知道哪个图像属于哪个数据。我知道我们无法将v模型绑定到输入文件,所以我尝试了另一种方式,但这也行不通。检查vue控制台,v模型文件为空。

Vue

<div class="row mt-2" v-for="(new_member,index) in new_members" :key="index">
    <div class="col-md-4">
        <label>NAME</label>
        <input class="form-control" type="text" v-model="new_member.name" required/>
    </div>
    <div class="col-md-4">
        <label>POSITION</label>
        <input class="form-control" type="text" v-model="new_member.position" required/>
    </div>
    <div class="col-md-4">
        <label>IMAGE</label>
        <input type="file" @change="onFileChange(index,$event)" name="file" ref="fileInput" required/>
    </div>
</div>
<button class="btn btn-primary col-md-2 col-12 rounded-0 float-right"  @click.prevent="addMoreMember()">ADD MORE</button>

<script>
data(){
    return{
        new_members:[{
            name:'',
            position:'',
            file:''
        }]
    }
},
methods:{
    addMoreMember(){
        this.new_members.push({name:'',position:'',file:''})
    },
    onFileChange(index,$event) {
        this.new_members[index].file =  $event.target.files[0]
    },
}
</script>

1 个答案:

答案 0 :(得分:1)

计算得出的猜测告诉我Vue没有检测到这些对象更改。参见https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

您可以在文档中使用Vue.set添加反应性属性,或尝试:

onFileChange(index,$event) {
   const member = this.new_members[index];
   this.new_members.splice(index, 1, {
      ...member,
      file: $event.target.files[0]
   });
},