Vue数据对象在被@change触发时没有反应

问题描述 投票:0回答:2

创建一个将显示上载文件内容的页面。但是我不明白为什么通过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>

CodeSandbox link

请帮助!谢谢

javascript node.js vue.js quasar
2个回答
0
投票

所以我现在可以使其工作。我修改了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);
    },

0
投票

this不是您的代码中位于[[FileReader中的Vue实例。当你写:

reader.onload = function()

this

成为onload函数(范围更改)。尝试const self = this

reader.onload

之前并在onload函数中使用self,或尝试使用fat arrow functionreader.onload = (e) => {}
© www.soinside.com 2019 - 2024. All rights reserved.