[Vuejs]-Understanding Vue components and fileupload

0👍

Okay just a few things

  • You need to use template rather than el when creating components.
  • Take the template out of the main document flow and use the corresponding component tag name as an element or use the inline-template property.
  • Don’t name components the same as any standard html tags.
  • Data should be a function.
Vue.component('v-form', {
        template: '#myform',
        data() {
          return{
            fileinput: ''
          };
        },
        methods: {
            onFileChange(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createInput(files[0]);
            },
            createInput(file) {
                var reader = new FileReader();
                var vm = this;
                reader.onload = (e) => {
                    vm.fileinput = reader.result;
                    console.log(vm.fileinput);
                }
                reader.readAsText(file);
            }
        }
});

new Vue({
  el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>

<div id="app">
  <v-form></v-form>
</div>

<template id="myform">
  <form enctype="multipart/form-data">
      <input type="file" @change="onFileChange">
  </form>
</template>

With inline-template, remove template from the component and define your html like this:

<div id="app">
  <v-form inline-template>
      <form enctype="multipart/form-data">
        <input type="file" @change="onFileChange">
      </form>
  </v-form>
</div>

Leave a comment