MultiUpload 组件内容:

<template>
  <div>
    <el-upload
      :action="uploadUrl()"
      list-type="picture-card"
      accept=".jpg,.jpeg,.png,.gif"
      multiple
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" :alt="dialogImageName">
    </el-dialog>
  </div>
</template>
<script>

import { getImageUpload } from '@/api/badFruit'
export default {
  name: 'MultiUpload',
  props: {
    // 图片属性数组
    value: {
      type: Array,
      default: () => []
    },
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      fileList: [],
      imagesList: [],
      images: [],
      dialogVisible: false,
      dialogImageUrl: null,
      dialogImageName: '',
      num: 0,
      fileNum: 0
    }
  },
  created() {
    // 上传组件显示列表
    this.fileList = this.value
    // 图片保存数组
    this.imagesList = this.value
  },
  methods: {
    // 文件上传地址
    uploadUrl() {
      return getImageUpload
    },
    handleRemove(file, fileList) {
      const list = JSON.parse(JSON.stringify(fileList))
      this.imagesList = list.map(item => ({
        name: item.name,
        url: item.url
      }))
      this.$emit('input', this.imagesList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
      this.dialogImageName = file.name
    },
    handleUploadSuccess(res, file) {
      // console.log(res, file)
      if (res.code === '200') {
        const { message, path } = res.data
        if (message === '图片上传成功') {
          this.images.push({
            name: file.name,
            url: path
          })
          this.num++
          if (this.num === this.fileNum) {
            this.num = 0
            this.fileNum = 0
            // 这里如果 this.value.push(imageUrl) 这么写,vue会报出警告,大概意思是value作为props不应该在子组件中被修改
            // 应该根据 value 得到新的值,而不能修改它,this.value.concat(imageUrl)也是可以的,concat方法返回新的数组
            this.$emit('input', this.imagesList.concat(this.images))
            this.images = []
          }
        }
      }
    },
    handleBeforeUpload(file) {
      this.fileNum++
      console.log('上传个数:' + this.fileNum)
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '张图片',
        type: 'warning',
        duration: 1000
      })
    }
  }
}
</script>
<style scoped lang="scss">

</style>


使用方式:

	// 模板
      <el-form-item label="坏果图片">
        <!--<el-input v-model="form.image" />-->
        <multi-upload v-model="form.image" @input="getImages" />
      </el-form-item>
	// 方法
    getImages(images) {
      console.log(images)
      this.form.image = images
    },

Logo

前往低代码交流专区

更多推荐