首页 > 解决方案 > 面临向对象 JS 添加属性的问题

问题描述

我正在尝试将属性添加到文件对象。我正在添加这样的属性(我正在使用 Vue):

<input type="file" id="fileUpload" name="file" @change="setToUploadStatus" multiple>

setToUploadStatus 方法:

setToUploadStatus (event) {
    let files = event.target.files

    Array.from(files).forEach((file) => {
        let id = this.randomString(10)
        file.id = id
        this.uploadStatus.push({
            id: id,
            name: file.name,
            uploading: false,
            uploaded: false
        })
    }

    this.uploadFile(files)
}

上传文件方法:

async uploadFile (files) {
    for (const file of files) {
        // Upload file with axios
    }
}

随机字符串方法:

randomString (length) {
  let text = ''
  let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (var i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length))
  }
  return text
}

我的问题是它并不id总是添加属性。有时它会添加有时不会。Specially when many files are selected. 这是一个日志https://prnt.sc/kxsqhi

我究竟做错了什么?请帮忙!

在此处转换为片段:

setToUploadStatus(event) {
    let files = event.target.files

    Array.from(files).forEach((file) => {
        let id = this.randomString(10)
        file.id = id
        this.uploadStatus.push({
          id: id,
          name: file.name,
          uploading: false,
          uploaded: false
        })
      }

      this.uploadFile(files)
    }

    async uploadFile(files) {
      for (const file of files) {
        // Upload file with axios
      }
    }

    randomString(length) {
      let text = ''
      let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      for (var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length))
      }
      return text
    }
<input type="file" id="fileUpload" name="file" @change="setToUploadStatus" multiple>

标签: javascriptvuejs2

解决方案


首先,从您提供的代码来看,它没有任何问题。也许问题来自其他地方。

其次,我看到您想为id每个文件赋予唯一性。生成随机字符串很好,但仍然有可能两个random字符串相同。所以这里有一个简单的方法来解决这个问题。

new Vue({
  el: "#app",
  data: {},
  methods: {
    updateFile(event) {
      let files = event.target.files
      let uid = 0;
      Array.from(files).forEach(file => {
        file.id = ++uid;
        console.log(file);
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <input type="file" multiple @input="updateFile" />
</div>

这个实现很简单。

这是 JSFiddle 链接:https ://jsfiddle.net/clintonyeb/3qreb1L9/


推荐阅读