FileReader 方法不更新数据属性(vue.js)

eru*_*rup 0 filereader fileapi vue.js

我试图在vue.jsvia 中加载一个 JSON 文件FileReader。JSON 文件通过BoostrapVue的表单文件输入作为 javascript File 对象实例加载。这是我当前的App.vue文件:

<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>
Run Code Online (Sandbox Code Playgroud)

一旦我更新了 JSON 文件,json应该用它更新并传递给ChildComponent将显示它的某些部分的 。不幸的是,结果json属性是空的,就像它没有被read()方法更新一样。我不明白我错在哪里。

Ohg*_*why 5

你是对的,它没有更新。上下文this的范围内anonymous function变化。

reader.onload = function(event) {
  this.json = JSON.parse(event.target.result);
}.bind(this);
Run Code Online (Sandbox Code Playgroud)

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

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

reader.onload = (event) => {
  this.json = JSON.parse(event.target.result);
}
Run Code Online (Sandbox Code Playgroud)