Search code examples
vue.jsfilereaderfileapi

FileReader method does not update data property (vue.js)


I trying to load a JSON file in vue.js via FileReader. The JSON file is loaded via the form file input of BoostrapVue as a javascript File object instance. Here is my current App.vue file:

<template>
    <div v-if="fileUploaded">
        <div class="rf">
            <ChildComponent v-bind:json="json"/>
        </div>
    </div>
    <div v-else>
        <!-- BoostrapVueFileInput -->
    </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
name: 'rf',
data () {
    return {
    fileUploaded: false,
    file: null,
    json: null
    }
},
methods: {
    read() {
    var reader = new FileReader();
    reader.onload = function(event) {
        this.json = JSON.parse(event.target.result);
    };
    reader.readAsText(this.file);
    }
}
}
</script>

Once I update the JSON file, the json should be updated with it and passed to the ChildComponent that will display some part of it. Unfortunately, the resulting json property is empty, like if it was not updated by the read() method. I don't understand where I am wrong.


Solution

  • You're right, it's not being updated. The context of this within an anonymous function changes.

    reader.onload = function(event) {
      this.json = JSON.parse(event.target.result);
    }.bind(this);
    

    In your case you can simply just use the bind method.

    If you're transpiling downwards anyway, you can use the fat arrow method:

    reader.onload = (event) => {
      this.json = JSON.parse(event.target.result);
    }