Vue event $refs test

Vue event $refs test

by seo gyeongseok

HTML

<div id="app">
  <image-upload></image-upload>
</div>

<template id="myTest">
  <div class="image-upload">
    <input
      ref="fileInput"
      type="file"
      @change="onChangeFileInput"
    >
    <div
      class="uploadButton"
      ref="uploadButton"
      @click.stop.prevent="onClickUploadButton">
      upload
    </div>
    <div
      class="uploadThumbnail"
      ref="uploadThumbnail">
      thumbnail
    </div>
  </div>
</template>

SCSS

.image-upload {
    input {
        display: none;
    }

    .uploadButton {
        border-color: #344bb8;
        border-style: dotted;
    }

    .uploadThumbnail {
        width: 300px;
        height: 400px;
        border: 1px solid black;
    }
}

JavaScript

Vue.component('image-upload', {
  template: '#myTest',
  name: 'image-upload',
  props: {
    thumbnail: {
      type: Object,
      default: null
    },
    imageURL: {
      type: String,
      default: ''
    },
    isGallyMode: {
      type: Boolean,
      default: false
    },
    isDragAndDropSupport: {
      type: Boolean,
      default: false
    },
    isShowUploadProgress: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      refs: null
    }
  },
  methods: {
    onChangeFileInput () {
      const file = this.$refs.fileInput.files[0]

      // TODO: image type check
      const fileReader = new FileReader()
      fileReader.onprogress = function (evt) {
        if (evt.lengthComputable) {
          const { loaded, total } = evt
          console.log(`File load progress > ${loaded}/${total}`)
        }
      }

      fileReader.onloadend = function (evt) {
        const { error } = evt.target

        if (error) {
          // TODO: file read fail event emit with error code
          console.error(`File could not be read! Code ${error.code}`)
        } else {
          console.log('File load complete !')
        }
      }

      fileReader.onload = (evt) => {
        // TODO: check image size
        const dataURL = fileReader.result
        const img = new Image()
        img.src = dataURL

        this.$refs.uploadThumbnail.appendChild(img)
      }

      // read file data
      fileReader.readAsDataURL(file)
    },

    onClickUploadButton () {
      this.$refs.fileInput.click()
    }
  },
  mounted () {
    this.$data.refs = this.$refs
    console.log('mounted', this.$refs, this.$data)
    console.log(this)
    this.onClickUploadButton = this.onClickUploadButton.bind(this)
  }
});

var vm = new Vue({
  el: '#app'
});