ant-design-vue a-upload 多圖上傳並拖拽排序

在這裏插入圖片描述
說下思路,ant自己的a-upload組件,不好套拖拽,因爲我們需要拖拽的是fileList,所以我就把組件自己的fileList搞成空了,自己寫了一個‘fileList’,這樣我們用數據自己循環出來的filelist就可以進行很多操作了。

1.我是把a-upload寫成了一個組件,
在組件裏用了vue-draggable進行拖拽
先安裝 npm install vuedraggable
新建組件文件,路徑:src/components/UploadImage/UploadImage.vue
組件見代碼

<template>
  <div class="myFileList">
    <a-spin :spinning="confirmLoading">
      <a-upload
      listType="picture"
      class="upload-list-inline"
      :fileList="[]" // 看到沒,這裏爲空
      :customRequest="uploadImage"
      :beforeUpload="beforeUpload"
      :multiple="true"
    >
      <a-button>
        <a-icon type="upload" /> 上傳附件
      </a-button>
    </a-upload>
    //  這裏就是我自定義的一個圖片展示列表,只是用了上傳組件的樣式,你想自己排樣式也可以,我覺得他這個樣式比較好看
      <div class="ant-upload-list ant-upload-list-picture">
        <draggable
          class="syllable_ul"
          element="ul"
          :list="fileList"
          :options="{group:'title', animation:150}"
          :no-transition-on-drag="true"
          @change="change"
        >
          <transition-group type="transition"  :name="!drag? 'syll_li' : null" :css="true">
           <div class="ant-upload-list-item ant-upload-list-item-done" v-for="(item, index) in fileList" :key="index">
          <div class="ant-upload-list-item-info">
            <span><a :href="item.url" target="_blank" rel="noopener noreferrer" class="ant-upload-list-item-thumbnail"><img :src="item.url" alt="4.jpg"></a><a target="_blank" rel="noopener noreferrer" title="4.jpg" :href="item.url" class="ant-upload-list-item-name">{{item.name}}</a></span>
          </div>
          <i aria-label="圖標: close" tabindex="-1" class="anticon anticon-close" @click="removeCoupon(item.uid)" ><svg viewBox="64 64 896 896" data-icon="close" width="1em" height="1em" fill="currentColor"><path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path></svg></i>
        </div>
          </transition-group>
        </draggable>
      </div>
    </a-spin>
  </div>
</template>
<script>
import { axios } from '@/utils/request'
import draggable from 'vuedraggable'
export default {
  name: 'UploadImage',
  props: {
    multiple: {
      type: Number,
      default: 1
    },
    img: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      fileList: [],
      imageId: [],
      files: [],
      a: [],
      confirmLoading: false,
      drag: false
    }
  },
  components: {
    draggable
  },
  methods: {
  // 需要把排序過後的數據 傳給父組件
    change (evt) {
      this.$emit('draggable', this.fileList)
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/bmp'
      if (!isJPG) {
        this.$notification['error']({
          message: '請上傳圖片文件'
        })
      }
      // const isLt2M = file.size / 1024 < 200 && file.size / 1024 > 10;
      // if (!isLt2M) {
      //   this.$message.error('文件大小應在10KB~20KB之間');
      // }
      // return isJPG && isLt2M
      return isJPG
    },
    removeCoupon: function (file) {
      this.fileList.forEach((val, key) => {
        if (file === val.uid) {
          this.fileList.splice(key, 1)
          this.$emit('delimageId', key)
        }
      })
    },
    // 圖片預覽
    uploadImg: function (e) {
      let _this = this
      if (!e || !window.FileReader) return
      let reader = new FileReader()
      reader.readAsDataURL(e.file)
      reader.onloadend = function () {
        _this.uploadImage()
      }
    },
    uploadImage: function (e) {
      this.confirmLoading = true
      let formdata = new FormData()
      formdata.append('file', e.file)
      axios({
        url: '/api/file/upload',
        method: 'post',
        data: formdata
      }).then((res) => {
        this.confirmLoading = false
        if (this.multiple === 1) {
          this.fileList = [{
            uid: '-1', // 文件唯一標識,建議設置爲負數,防止和內部產生的 id 衝突
            name: e.file.name, // 文件名
            status: 'done', // 狀態有:uploading done error removed
            url: this.GLOBAL.imgUrl + res.result.fileId
          }]
        } else {
          if (this.fileList.length < this.multiple) {
            this.fileList.push({
              uid: '-' + (this.fileList.length + 1), // 文件唯一標識,建議設置爲負數,防止和內部產生的 id 衝突
              name: e.file.name, // 文件名
              status: 'done', // 狀態有:uploading done error removed
              url: this.GLOBAL.imgUrl + res.result.fileId
            })
          }
        }
        this.$emit('getImageId', res.result.fileId)
      })
    }
  },
  mounted () {
    if (this.img.length > 0) {
      this.img.forEach((val, key) => {
        this.fileList.push({
          uid: '-' + key, // 文件唯一標識,建議設置爲負數,防止和內部產生的 id 衝突
          name: '' + val.name, // 文件名
          status: 'done', // 狀態有:uploading done error removed
          url: '' + val.url
        })
      })
    }
  }
}
</script>
<style>
  ul{
    padding: 0;
  }
  // 因爲我們用的ant的組件的class,會有些默認樣式要去掉,如果樣式是你自己寫的,那就不需要這塊了
    .ant-upload-list{
    display: block !important
  }
</style>

2.使用
import UploadImage from ‘…/…/…/components/UploadImage/UploadImage’
components: {
UploadImage
},
(1)添加頁面,不需要圖片回顯

<upload-image @getImageId="getImageId" @delimageId="delimageId" :multiple="1"></upload-image>
// 看到multiple了嗎,後面的數字爲改組件允許最多傳多少張,如果不限制圖片張數的話,寫999就可以了
   // 產品封面圖片預覽
    getImageId: function (val) {
      this.imageId.push(val)
    },
    // 刪除產品封面圖片
    delimageId: function (index) {
      this.imageId.forEach((val, key) => {
        if (index === key) {
          this.imageId.splice(key, 1)
        }
      })
    },
    // 這裏兩個方法獲取的imageId,是我晚點要傳給後臺的數據

(2)編輯頁面,需要回顯圖片
單張回顯:

<upload-image @getImageId="getImageId" @delimageId="delimageId" :multiple="1" :img="[{name: proDel.title, url: imgUrl}]" v-if="lock"></upload-image>
    // 圖片預覽
    getImageId: function (val) {
      this.imageId = []
      this.imageId.push(val)
    },
    // 刪除圖片
    delimageId: function (index) {
      this.imageId.forEach((val, key) => {
        if (index === key) {
          this.imageId.splice(key, 1)
        }
      })
    },
多張回顯:
 <upload-image @getImageId="getDelImageId" @delimageId="delDelimageId" :multiple="99" :img="showContent" @draggable="handleDraggable" v-if="lock"></upload-image>
 if (!res.result.content) {
            this.showContent = []
          } else {
            var ss = res.result.content.split(',')
            this.showContent = ss.map(item => ({ name: res.result.title, url: this.GLOBAL.imgUrl + item }))
          }
//res.result.content 是我從接口獲取的數據,把數據拼接一下,搞成我們需要的格式

    // 產品詳情圖片預覽
    getDelImageId: function (val) {
      this.imageDelId.push(val)
    },
    // 刪除產品詳情封面圖片
    delDelimageId: function (index) {
      this.imageDelId.forEach((val, key) => {
        if (index === key) {
          this.imageDelId.splice(key, 1)
        }
      })
    },   
        // 獲取到重新排序後的圖片
    handleDraggable (e) {
      const imgDrag = []
      for (var i = 0; i < e.length; i++) {
        var a = e[i].url.split('/')
        imgDrag.push(a[3])
      }
      this.imageDelId = imgDrag
    },       

// 上面兩個使用,組件裏都有一個v-if="lock"看到沒,這個lock,初始爲false,等到我們從接口把數據都獲取了,再設置爲true

 getProductDel(data).then((res) => {
        this.confirmLoading = false
        if (res.errorCode === 0) {
          this.imageId = res.result.imgs.split(',')
          // 用了this.$nextTick
          this.$nextTick(() => {
            this.lock = true
          })
        } else {
          this.$notification['error']({
            message: res.errorMsg
          })
        }
      })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章