I'm using VueJS
with vuetify
. I have an input tag and button which triggers function @click
, once I change to v-file-input
component I get an error.
Here is the code - script and template:
<script>
import papa from "papaparse";
export default {
name: "CompareInput",
data() {
return {
csvData: [],
};
},
methods: {
csvToJson() {
let csvFile = this.$refs.file.files[0];
if (csvFile == undefined) {
alert("Please select a file to convert");
this.csvData = [];
return;
}
papa.parse(csvFile, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
preview: 100,
complete(result) {
this.csvData = result.data;
for (let item of this.csvData) {
console.log(item.input_fullName);
}
console.log(this.csvData);
},
});
},
},
};
</script>
<template>
<div >
<h3>CSV Parser</h3>
<v-file-input multiple ref="file" type="file"> </v-file-input>
<v-btn @click="csvToJson" >Submit</v-btn>
</div>
</template>
The error - Cannot read properties of undefined (reading '0')
Again, everything works fine with the regular input tag.
CodePudding user response:
I guess you misunderstood @JenifferJin answer.
Your error is on this line:
let csvFile = this.$refs.file.files[0];
You are referencing v-file-input
component, but trying to work with it as with native HTML input
tag. This should not be done.
v-file-input
does not contain files field directly. You can see this for yourself if you write something like this and look into browser console:
...
csvToJson() {
console.log(this.$refs.file)
...
}
...
When you are working with v-file-input
, you should use v-model to store your file (or files).
So the answer is:
<v-file-input
v-model="filesModel"
multiple
type="file">
</v-file-input>
...
data() {
return {
filesModel: [],
};
},
...
methods: {
csvToJson() {
if (this.filesModel === null
|| this.filesModel === undefined
|| this.filesModel.length === 0) {
alert("Please select a file to convert");
return;
}
let csvFile = this.filesModel[0];
...the rest of your code
},
},
There's a CodePen that may help you to understand the difference between v-file-input
and input
.
CodePudding user response:
Here is my experience:
<v-file-input
show-size counter
accept="video/*"
v-model="video"
@change="onVideo"
>
</v-file-input>
in methods of Vue.js:
onVideo: function () {
console.log(this.video)
}