1. 程式人生 > >基於vue element 封裝上傳元件

基於vue element 封裝上傳元件

 基於vue element封裝的上傳元件

使用方法:

1.首先引入該元件

2.註冊元件

3.頁面使用

4.回撥函式(如需其他回撥自行封裝 因為我暫時沒用到其他的  哈哈哈)

 


<template>
  <div>
    <el-upload
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :before-upload="beforeAvatarUpload"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :http-request="uploadFile"
      :accept= "accept"
      action=""
      class="upload-demo">
      <el-button size="small" type="primary">點選上傳</el-button>
      <div slot="tip" class="el-upload__tip">只能上傳{{ seeTrans[uploadType] }}檔案,且不超過16Mb</div>
    </el-upload>
  </div>
</template>
<script>
//    :on-success="handleAvatarSuccess"
import { uploadImg, uploadMusic,uploadPdf,uploadDoc } from '@/api/upload.js'
import elDragDialog from '@/directive/el-dragDialog/index'
export default {
  directives: { elDragDialog },
  components: { imgShow },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    uploadType: {
      type: String,
      default: () => 'images'
    }
  },
  data() {
    return {
      uploadTypeTrans: {
        'photo': {
          urlPath: uploadImg,
          accept: 'image/jpeg,image/png,image/bmp'
        },
        'music': {
          urlPath: uploadMusic,
          accept: 'audio/mp3,video/mp4'
        },
        'doc': {
          urlPath: uploadDoc,
          accept: 'text/plain,application/msword,application/excel,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        },
        'pdf':{
          urlPath: uploadPdf,
          accept: 'application/pdf'
        }
      },
      accept: 'image/jpeg,image/png,image/bmp',
      dialogVisible: false,
      seeTrans: { music: '歌曲', photo: '圖片' },
      onClosed: () => {}
    }
  },
  mounted() {
    if (this.uploadType && this.uploadTypeTrans[this.uploadType].accept) {
      this.accept = this.uploadTypeTrans[this.uploadType].accept
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      // 判斷圖片型別和大小
      const isLt16M = file.size / 1024 / 1024 < 16

      if (!isLt16M) {
        this.$message.error('上傳檔案大小不能超過 16MB!')
      }
      return isLt16M
    },

    handleRemove(file, fileList) { // 刪除圖片
      console.log(file, fileList)
      this.fileList.map((v, index) => {
        if (v.name === file.name) {
          this.fileList.splice(index, 1)
          this.$emit('getFileList', this.fileList)
        }
      })
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`確定移除 ${file.name}?`, {
        confirmButtonText: '確認',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },

    async uploadFile(file) {
      try {
        console.log(file)
        const formData = new FormData()
        formData.append(this.uploadType, file.file)
        const res = await this.uploadTypeTrans[this.uploadType].urlPath(formData)
        if (res.error_code === 0) {
          res.data.map(v => {
            this.fileList.push({ name: file.file.name, url: v.file_url })
          })
          this.$emit('getFileList', this.fileList)
          this.$emit('fileSize', file.file.size)
          this.$message.success('上傳成功')
        }
        console.log(this.fileList)
      } catch (error) {
        this.fileList.pop()
        this.$message.error(`上傳檔案錯誤: ${error.message}`)
      } finally {
         // /// 寫點啥呢?
      }
    },

    handlePreview(file) { // 檢視圖片
      const data = {
        file: file,
        type: this.uploadType
      }
      this.$emit('showFile', data)
    },

    // handleAvatarSuccess(response, file) { // 上傳圖片回撥
    //   // this.fileList.push(file)
    //   console.log(response)
    //   alert(1)
    // },

    handleExceed(files, fileList) {
      this.$message.warning(`當前限制選擇 1 個檔案,本次選擇了 ${files.length} 個檔案,共選擇了 ${files.length + fileList.length} 個檔案`)
    }
  }
}
</script>