(I’m using vue 3) I’m adding files from input file to array, then I conditionally render these file names. All working good on Chrome. Problem is when using Mozilla Firefox. In this browser array of files is overrided by last added file, for example:
- add file-1 || output: file-1
- add file-1 and next file-2 || output: file-1 file-1 (duplication).
There you can view and test this code: https://codesandbox.io/s/elegant-poitras-exux2z?file=/src/App.vue
method:
JavaScript
x
5
1
methods: {
2
addFile (file) {
3
this.form.files.push(file);
4
}}
5
data structure:
JavaScript
1
6
1
data() {
2
return {
3
form: {
4
files: [],
5
}};},
6
output:
JavaScript
1
7
1
<div>
2
<input @input="addFile($event.target.files)" type="file" name="" id="">
3
<p v-for="file in form.files" :key="file">
4
{{ file[0].name }}
5
</p>
6
</div>
7
Advertisement
Answer
Got a fix for you
JavaScript
1
6
1
methods: {
2
addFile(file) {
3
this.form.files.push({ file });
4
}
5
}
6
Reason is – well, my theory is that $event.target.files
is not a new object every time addFile($event.target.files)
is called
You’ll see this if you change your code to
JavaScript
1
9
1
methods: {
2
addFile(file) {
3
if (this.form.files.length) {
4
console.log(this.form.files[0] === file)
5
}
6
this.form.files.push(file);
7
}
8
}
9
This logs true in Firefox 103, but false in Firefox 104 (dev version)
Another alternative
JavaScript
1
10
10
1
<p v-for="file in form.files" :key="file">
2
{{ file.name }}
3
</p>
4
5
methods: {
6
addFile(file) {
7
this.form.files.push(file[0]);
8
},
9
}
10