创建一个将显示上载文件内容的页面。但是我不明白为什么通过msg
触发show
和@change
数据参数时未更新。我只需要在文件上传成功的情况下更新这两个参数,所以这就是为什么将它们放在onload
函数lambda中的原因:
reader.onload = function(e) {
this.msg = e.target.result;
this.show = true;
console.log(this.msg);
}
还请注意,console.log(this.msg)
正确记录了文件内容。那么为什么孩子没有得到这些改变呢?
我也尝试通过单击按钮进行设置,效果很好。
这是我的代码(App.vue):
<template>
<div id="q-app">
<router-view></router-view>
<input type="file" ref="file" @change="changeViaUpload">
<br><br>
<button @click="changeViaButton">Update data via Button</button>
<hello :show=show :msg=msg></hello>
</div>
</template>
<script>
import hello from '../components/Hello.vue'
export default {
name: "app",
components:{
hello
},
data() {
return {
msg: "",
show: false
};
},
methods: {
changeViaUpload(ev) {
const file = ev.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
this.msg = e.target.result;
this.show = true;
console.log(this.msg);
};
reader.readAsText(file);
},
changeViaButton() {
this.msg = "Message has been changed via button";
this.show = true;
}
}
};
</script>
这是我的Hello.vue
:
<template>
<div v-if="show">
<!-- <div> -->
[Hello.vue] This div will be shown if boolean show is true
<br>
{{ msg }}
</div>
</template>
<script>
export default {
props: ['msg','show'],
data() {
return {
};
},
methods: {
}
};
</script>
请帮助!谢谢
所以我现在可以使其工作。我修改了changeViaUpload()
以使用:
var vm = this;
并通过vm.msg
更新参数
摘要:
changeViaUpload(ev) {
const file = ev.target.files[0];
const reader = new FileReader();
var vm = this;
reader.onload = function(e) {
vm.msg = e.target.result;
vm.show = true;
console.log(vm.msg);
};
reader.readAsText(file);
},
this不是您的代码中位于[[FileReader中的Vue实例。当你写:
reader.onload = function()
成为onload函数(范围更改)。尝试this
const self = this
在之前并在onload函数中使用self,或尝试使用fat arrow functionreader.onload
reader.onload = (e) => {}