Anyone can help explain the described behavior above ? Thanx :)
VueJS csv Filereader
Hi Folks,
I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).
My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )
html:
<form enctype="multipart/form-data">
<input type="file" @change="onFileChange">
</form>
JS:
new Vue({
el: '#app',
data: {
fileinput: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createInput(files[0]);
},
createInput(file) {
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.fileinput = reader.result;
}
reader.readAsText(file);
console.log(this.fileinput);
}
}
})
@ssn wow Thats a long time ago :D
I posted the same question later to stackoverflow: https://stackoverflow.com/questions/34498596/vuejs-csv-filereader
David K. Rees answered the following:
"The reason why the console.log is not displaying anything is because FileReader.readAsText() is asynchronous. It completes after the console.log has executed.
You can typically deal with this by putting a watch on fileInput or throwing a local event using vm.$emit from the onload handler."
Please or to participate in this conversation.