封装上传图片组件

import Upload from './components/upload.vue'
Vue.component('Upload', Upload)

子组件

<template>
    <div class="InputImg">
        <div style="position: relative;width: 100%;height:100%">
            <div @click="imgclick" style="width: 100%;height: 100%;padding:0;left:0;top: 0;">
                <img v-if="Images!=''" :src="Images" alt="" class="logobtn" id="logo_img" style="width: 100%;height: 100% !important;padding:0;left:0;top: 0"/>
            </div>
            <input type="file" ref="filElem" :data-id="Id" @change="filechange" name="logo" accept="" style="display:none"/>
            <img class="DelIcon" v-show="Del" :data-id="Id" @click="DelClick" src="../assets/delicon.png">
        </div>
    </div>
</template>
<script>
export default {
  props: ['Images', 'Del', 'Id', 'Fd'],
  methods: {
    imgclick () {
      this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
    },
    filechange () {
      var file = this.$refs.filElem.files[0]
      var fd = new FormData()
      if (file !== undefined && file != null && file !== '') {
        fd.append('file', file)
        this.uploadLogo(file, fd)
      }
    },
    DelClick () {
      let allData = {
        Images: '',
        Del: false,
        Fd: null
      }
      this.$emit('uploadRes', allData)
    },
    async uploadLogo (file, fd) {
      var that = this
      try {
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
          let allData = {
            Images: this.result,
            Del: true,
            Fd: fd
          }
          that.$emit('uploadRes', allData)
        }
      } catch (error) {
        alert(error)
      }
    }
  }
}
</script>

父级

html

<Upload class="ThumbnailUpload" :Images = ThumbnailImages :Del = ThumbnailDel :Id = ThumbnailId :Fd = ThumbnailFd @uploadRes="uploadRes($event)"></Upload>
script
data () {
    return {
        ThumbnailImages: '',
        ThumbnailDel: false,
        ThumbnailId: '',
        ThumbnailFd: ''
    }
  },
methods: {
    uploadRes (res) {
      this.ThumbnailImages = res.Images
      this.ThumbnailDel = res.Del
      this.ThumbnailFd = res.Fd
    }
}

 

posted @ 2019-09-04 17:53  略略略额  阅读(177)  评论(0)    收藏  举报