0

Today I find a bug which happened in Chrome but run well in Firefox. It's a upload component which like this:

<input type="file" v-on:change="upload($event)"/>

upload(e) {
  this.name = e.target.files[0].name;
  this.resultUrl = e.target.files[0];
}

I choose a file and then rechoose and cancel, I found the page is stopped. What's worse is that the console doesn't have any error messages. So I have to guess what caused the bug.
I used sometime and realized the error may in the component. So I add a print console.log(e.target.files) in upload method. As I excepted, the Chrome's print is different with Firefox's print. Chrome has two print and Firefox just one. This is Chrome's print.
Chrome's Print
And then I found this input type=“file”, clearing file after clicking cancel in chrome. I have known what caused the bug and fixed it by adding a judge.
But this is not the first time I meet the page stopped with no error message on console. So how to throw and deal with the error happened in vue component?

Yukino
  • 37
  • 1
  • 8

1 Answers1

0

To stop your error, you just need to check if a file exists before doing .name, because if no file exists you'll get an error for doing undefined.name. I've built a fiddle below based on the code you provided.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  data: () => {
    return {
      name: null,
      resultUrl: null
    }
  },
  methods: {
    uploadFile: function(ev) {
      let file = ev.target.files[0];

      if (!file) {
        this.name = null;
        this.resultUrl = null;
        return;
      }

      this.name = file.name;
      this.resultUrl = file;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="file" @change="uploadFile" />
</div>
Shoejep
  • 4,414
  • 4
  • 22
  • 26
  • Thanks your answer, I had added a judge before doing .name. What I want to know is why the component's error didn't be printed in console and is there a way to expose the error and deal with it. Because I have met several times the component's error didn't printed in console and page crash. – Yukino Dec 31 '20 at 09:53
  • @Yukino It could be loads of things, I get an error when using `e.target.files[0].name` when no files are provided, so it's like how is your setup different to the fiddle. Could be something in your setup or in your browser. I would double check your browser console to make sure there's no filters selected. – Shoejep Dec 31 '20 at 10:51