<script src="//unpkg.com/vue@2/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.15.14/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<el-upload
  class="upload-demo"
  :name="uploadId"
  :ref="`Uploader-${uploadId}`"
  action=""
  list-type="picture-card"
  :on-remove="handleRemove"
   accept="image/*"
   multiple
  :file-list="fileList"
  :on-change="handleChange"
  :http-request="httpRequest"
  :auto-upload="false"
 >
  <el-button slot="trigger" size="small" type="primary">选取文件
  </el-button>
</el-upload>
</div>
var Main = {
    data() {
      return {
        fileList: [],
        uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),
        uploadFiles: [],
        fm: new FormData(),
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
    // 选择文件时,往fileList里添加
    handleChange(file, fileList) {
     //获取添加文件进来的状态
     (file.status == 'ready') && this.uploadFiles.push(file.raw);
     //获取原始文件的个数
     this.fileTotal = document.getElementsByName(this.uploadId)[0].files.length;
     //如果原始文件和upload的个数相同的时候就说明已经添加完了,可以触发上传的方法了
     if (this.uploadFiles.length === this.fileTotal) {
         //获取上传文件的组件
         const Uploader = this.$refs[`Uploader-${this.uploadId}`];
         //触发上传文件列表的方法
         Uploader.submit();
     }
    },
    // 批量上传
    httpRequest(file) {
      this.fm.append('file', file.file);
      if (this.fm.getAll('file').length === this.fileTotal) {
          this.$axios.post('https://jsonplaceholder.typicode.com/posts/', this.fm).then(res => {
            this.$message.success('图片上传成功!')
          }).catch(res => {
            this.$message.success('图片上传失败!')
          })
      }
      this.fileList = [];
    }
  }
}
Vue.prototype.$axios = axios
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
Logo

前往低代码交流专区

更多推荐