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

更新日期: 2019-11-21 阅读次数: 22193 字数: 204 分类: VueJS

在 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 聊聊, 查看更多联系方式

谈笑风生

小飞侠

用onchange不香吗?直接把回调的fileList赋值给data里面fileList

Raymond

elementui 的 el-upload 的 ref 的值是一个Array : 
```
this.$refs.uploada // uploada: (3) [VueComponent, VueComponent, VueComponent]
```

通过下标可以取得对应值。

---


换句话说,得这样取汁:
```
console.log(this.$refs.uploada[0].uploadFiles)
console.log(this.$refs.uploada[1].uploadFiles)
console.log(this.$refs.uploada[2].uploadFiles)
```