vue 中 el-upload ,el-image-viewer实现图片列表上传预览图片(二次改造)下载删除

637 阅读1分钟
   <el-row>
            <el-col :span="24">
              <el-form-item label="附件:">
                <el-upload action="#" list-type="picture-card" :on-change="imgHandleChange" :file-list="fileList" :auto-upload="false" accept=".jpg, .JPG, .png, .PNG, .bmp, .BMP">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePreview(file)">
                        <i class="el-icon-zoom-in" title="放大"></i>
                      </span>
                      <span v-if="!disabled && file.url.indexOf('blob') == '-1'" class="el-upload-list__item-delete" @click="handleDownload(file)">
                        <i class="el-icon-download" title="下载"></i>
                      </span>
                      <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <i class="el-icon-delete" title="删除"></i>
                      </span>
                    </span>
                  </div>
                  <div slot="tip" class="el-upload__tip">只支持格式为jpg、JPG、png 、PNG、bmp 、BMP的图片!</div>
                </el-upload>
                <el-image-viewer v-if="showImgViewer" :on-close="closeImgViewer" :url-list="imagePreviewUrls" :z-index="9999999999" :initial-index="initialImgPreviewIndex" />
              </el-form-item>
            </el-col>
          </el-row>

import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

data() {
return {

  fileList: [], // 图片列表
  initialImgPreviewIndex: 0,
  showImgViewer: false,
  imagePreviewUrls:[]

}

},

methods: {
closeImgViewer() {
  this.showImgViewer = false
},
// 图片上传
imgHandleChange(file, fileList) {
  if (!/\.(jpg|JPG|png|PNG|bmp|BMP)$/.test(file.name)) {
    this.$message({
      type: 'warning',
      message: '只支持格式为jpg/JPG/png/PNG/bmp/BMP的图片!'
    })
    fileList.pop()
    return false
  }
  this.fileList = fileList //把文件给data里的fileList


},

// 点击放大出发图片预览
handlePreview(file) {
  let index =  this.fileList.indexOf(file.url)
  if (index >= 0) {
  //判断是第几张图片
    this.initialImgPreviewIndex = index
  }
  this.showImgViewer = true
},
handleDownload(file) {
//根据图片的url 实现下载
  window.open(file.url, '_blank')
},
// 删除文件
handleRemove(file) {
  if (this.fileList.length) {
    for (let i = 0; i < this.fileList.length; i++) {
      const element = this.fileList[i]
      if (file.id == element.id) {
        this.fileList.splice(i, 1)
      }
    }
  }

},

  watch: {
fileList: {
  handler: function (val) {
    this.imagePreviewUrls = []
    if (this.fileList.length) {
      this.fileList.map(item => {
        this.imagePreviewUrls.push(item.url)
      })
    }
  },
  deep: true,
  immediate: true
}

},`