VueJS csv Filereader VueJS csv Filereader vue.js vue.js

VueJS csv Filereader


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.


Here's another way

        onFileChange: function(e) {            const file = e.target.files[0];            const reader = new FileReader();            reader.onload = e => console.log(e.target.result);            reader.readAsText(file);        },

Reference Creating a Vue.js File Reader Component Using the FileReader API


Here you can handle async code using Promise function

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) {      let promise = new Promise((resolve, reject) => {        var reader = new FileReader();        var vm = this;        reader.onload = e => {          resolve((vm.fileinput = reader.result));        };        reader.readAsText(file);      });      promise.then(        result => {          /* handle a successful result */          console.log(this.fileinput);        },        error => {          /* handle an error */           console.log(error);        }      );    }  }});