1

vue 2.x

i have a file array, each item contains a file input as well as other text input, user can click + icon to add a item and have to upload one file or delete one item.

it looks like following:

before

however, if i add two items and each item has a file, then i delete the first item, the file input(original second item) will be cleared too like :

after

that is :

Level A  a.pdf
Level B  b.pdf

if i delete first, then it changed to

Level B no file selected

why? how to solve it?

my vue code is:

<tr v-for=" (a, index) in eb.attachmentList" v-bind:key="index">

<td>
<select v-model="a.typeId" required>
<option value="1">Level A</option>
<option value="13">Level B</option>
<option value="8">Level C</option>
</select>
</td>

<td><input type="text" v-model="a.description" /></td>

<td>
<input v-if="!a.eaId" type="file" v-on:change="selectFile(index, $event)" ref="f" required />
<a v-if="a.eaId" href="#" v-on:click="downloadFile(a)">{{a.fileName}}</a>
</td>

<td><i class="far fa-trash-alt fa-lg" v-on:click="delAttachment(a, index)" style="color: red"></i>

</td>

</tr>       

data () {
  return {
  eb: {
   'attachmentList': []
  }

  }
},               

methods: {            

addAttachment() {

var a = {'typeId': '', 'description': '', 'file': ''};
this.eb.attachmentList.push(a);
},                            

selectFile( index, e ){

this.eb.attachmentList[index].file = e.target.files[0];
},               

delAttachment( a, index ) {

this.eb.attachmentList.splice(index, 1);

//and delete this attachment from database
}

}

1 Answer 1

1

Setting the key as your index causes problems when updating arrays.

Instead generate a unique id for your items:

var a = {'typeId': '', id: new Date().valueOf() };

Then set key to a.id

working example: https://jsfiddle.net/ellisdod/tg2yr9L8/

Sign up to request clarification or add additional context in comments.

1 Comment

great, thanks! but why it only affect file input if i use index as key? it seems that other types, e.g. select, text input, didn't be affected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.