簡體   English   中英

面對向對象JS添加屬性的問題

[英]Facing issue to add property to object 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)
}

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> 

首先,從您提供的代碼來看,它沒有任何問題。 也許問題出在其他地方。

其次,我看到您想為每個文件賦予唯一的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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM