vue.js - 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.
解决方案
你是对的,它没有被更新。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);
}
推荐阅读
- java - 需要在 Rest Call 中插入变量
- cloudera-cdh - 支持 OpenJDK 并升级到 CDH 6
- html - 双击时防止在 Chrome 中突出显示文本
- java - 如何使用单个流操作从对象中获取多个值?
- javascript - 如何在three.js中弯曲圆柱体?
- jquery - 先前声明的变量没有传递值
- acumatica - 如何在添加到 INItemPlan 的用户字段中保存值?
- sql - 重复的总行数超过
- python - 在序列化程序 Django Rest + Django JWT 中获取记录的用户信息
- python-3.x - 当我下载日期并转换为 DataFrame 时,我丢失了第一列的数据