面临向对象JS添加属性的问题

时间:2018-09-23 16:48:03

标签: javascript vuejs2

我正在尝试向文件对象添加属性。我正在添加这样的属性(我正在使用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)
}

uploadFile方法:

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

randomString方法:

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属性。有时它没有增加。特别是在选择了多个文件时。这是日志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>

1 个答案:

答案 0 :(得分:0)

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

第二,我看到您想为每个文件赋予唯一的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/

相关问题