【问题标题】:Vue data objects are not being reactive when triggered by @changeVue 数据对象在被 @change 触发时没有反应
【发布时间】:2020-05-04 05:52:24
【问题描述】:

创建一个显示上传文件内容的页面。但我不明白为什么msgshow 数据参数在通过@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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      this 不是 FileReader 的 onload 函数内代码中的 Vue 实例。当你写:

      reader.onload = function() {}
      

      this 成为该函数内的 onload(其范围发生变化)。试试

      const self = this
      

      reader.onload 之前并在 onload 函数中使用 self,或尝试使用 胖箭头函数

      reader.onload = (e) => {}
      

      胖箭头函数(或只是简单的箭头函数)有一个词法this,这意味着这些函数内部的作用域不会改变。

      来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多