0

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.

1 Answer 1

7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.