[Vuejs]-Can't set Vue data variable when using FileReader API

0👍

You’re calling orderFiles like it’s a method and you need to parse the json with JSON.parse() to use it as an object. In the code below I’ve put the unparsed string representation into this.stringJSON and i’ve put the parsed json into an array of objects in this.parsedJsonArray.

Try selecting two json files in the example.

Vue.component('v-form', {
  template: '#myform',
  data() {
    return {
      fileinput: '',
      // jsonData: [],
      parsedJsonArray: [],
      stringJSON: '',
      orderFiles: {},
    };
  },
  methods: {
    async jsonLoop(files) {
      const ourDiv = document.getElementById('Json');

      for (let file of files) {
        let self = this;
        let fr = new FileReader();
        fr.onload = (e) => {
          console.log("onload FIRED")
          let jsonResult = e.target.result;

          // add json to div text
          // ourDiv.textContent += jsonResult;

          // add unparsed json string to our data
          self.stringJSON += jsonResult;

          // adding parsed json to our jsonData as an array of objects
          self.parsedJsonArray = [...self.parsedJsonArray, JSON.parse(jsonResult)];
          console.log(self.parsedJsonArray);
        }
        fr.readAsText(file);
      }
    },
    loadFiles(e) {
      if (window.File && window.FileReader && window.FileList && window.Blob) {
        let files = Array.from(e.target.files)
        // sort files
        // let orderFiles = this.orderFiles(files)
        this.jsonLoop(files)
        console.log(this.jsonData) // undefined
      } else {
        alert('The File APIs are not fully supported in this browser. Please use a different browser');
      }
    }
  }
});

new Vue({
  el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
  <v-form></v-form>
  <div id="Json"></div>
</div>

<template id="myform">
    <form enctype="multipart/form-data">
        <input type="file" @change="loadFiles" multiple><br/><br/>
        String JSON: <span>{{ stringJSON }}</span>
    </form>
</template>

Leave a comment