Javascript 当@change触发时,Vue数据对象不是被动的
创建一个显示上传文件内容的页面。但我不明白为什么msg和show数据参数在通过@change触发时没有被更新。我只需要在文件上载成功时更新这两个参数,因此我将它们放在onload函数lambda中:Javascript 当@change触发时,Vue数据对象不是被动的,javascript,node.js,vue.js,quasar,Javascript,Node.js,Vue.js,Quasar,创建一个显示上传文件内容的页面。但我不明白为什么msg和show数据参数在通过@change触发时没有被更新。我只需要在文件上载成功时更新这两个参数,因此我将它们放在onload函数lambda中: reader.onload = function(e) { this.msg = e.target.result; this.show = true; console.log(this.msg); } 还要注意console.logthis.msg正确记录了文件内容。 那么为什么孩子没
reader.onload = function(e) {
this.msg = e.target.result;
this.show = true;
console.log(this.msg);
}
还要注意console.logthis.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>
救命啊!谢谢所以我现在可以让它工作了。我修改了changeViaUpload以使用: 并通过: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);
},
这不是FileReader的onload函数中代码中的Vue实例。当你写作时:
reader.onload = function() {}
这将成为其作用域更改的函数内的onload。试一试
const self = this
在reader.onload之前,在onload函数中使用self,或者尝试使用胖箭头函数
fat arrow函数或仅仅是arrow函数都有一个词法,这意味着这些函数中的作用域不会改变
资料来源:
reader.onload = function() {}
const self = this
reader.onload = (e) => {}