[Vuejs]-Vue data objects are not being reactive when triggered by @change

1👍

this is not the Vue instance in your code inside the FileReader’s onload function. When you write:

reader.onload = function() {}

this becomes the onload inside that function (its scope changes). Try

const self = this

before reader.onload and use self inside your onload function, or try using a fat arrow function

reader.onload = (e) => {}

fat arrow functions (or just simply arrow functions) have a lexical this, meaning the scope does not change inside such functions.

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

0👍

So I am now able to make it work. I modified changeViaUpload() to use:

var vm = this;

and update the param via: vm.msg

Snippet:

    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);
    },
👤kzaiwo

Leave a comment