[Vuejs]-How to handle the error in vue component?

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>

Leave a comment