Vue Element UI upload 组件上传文件之后 file list 依旧是空数组

文章目录

    在 element ui 的 GitHub issue 中搜索了一下,发现 upload 组件确实不支持自动更新 file list,需要手动在上传成功和删除的回调中处理文件列表同步。。。

    这个体验太差了。

    无奈只能手动实现,设置 on-success 和 on-remove 的回调处理。

    模板代码

    <div id="upload_file">
      <el-upload
        class="upload-demo"
        action="/api/upload"
        :on-success="handle_success"
        :on-remove="handle_remove"
        :on-preview="handlePreview"
        :before-remove="beforeRemove"
        multiple
        :limit="5"
        :on-exceed="handleExceed"
        :before-upload="uploadBefore"
        accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx"
        :file-list="fileList">
        <el-button size="small" type="primary">Click to Upload</el-button>
      </el-upload>
    </div>
    

    JS 代码

    var vm = new Vue({
      el: "#upload_file",
    
      data: {
        fileList: []
      },
    
      mounted: function() {
      },
    
      methods: {
        handle_remove(file, fileList) {
          var _tmp = this.fileList;
          for (var i = 0, len = _tmp.length; i < len; i++) {
            if (_tmp[i].name = file.name) {
              _tmp.splice(i, 1);
              break;
            }
          }
          this.fileList = _tmp;
        },
    
        handle_success(response, file, fileList) {
          this.fileList.push({
            name: file.name,
            url: file.response
          });
        },
    
        handlePreview(file) {
          console.log(file);
        },
    
        uploadBefore(file) {
          if (file.size > 10 * 1024 * 1024) {
            this.$message.error("File size exceeded 10M!");
            return false;
          }
        },
    
        handleExceed(files, fileList) {
          this.$message.warning(`Number of files exceeded 5!`);
        },
    
        beforeRemove(file, fileList) {
          return this.$confirm(`Remove ${ file.name }?`, {
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel'
          });
        }
      }
    });
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式