首页 > 解决方案 > 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.

标签: vue.jsfilereaderfileapi

解决方案


你是对的,它没有被更新。this变化中的上下文anonymous function

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

在您的情况下,您可以简单地使用该bind方法。

如果您无论如何都要向下编译,则可以使用以下fat arrow方法:

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

推荐阅读