簡體   English   中英

如何創建唯一鍵/用 array.push 替換其值?

[英]How do I create unique keys/replace its value with array.push?

我有動態生成的輸入,我需要將它們添加到數組中。

data(){
    return{
     picture: []
   };
}

我的模板中有這個:

  <ion-input  :ref="'picture'+n" :id="'picture'+n" @change="getPicture" accept=".jpeg, .png, .jpg" type="file"></ion-input>

我需要以正確的順序獲取輸入,所以我創建了一個關聯數組,將每個輸入的 id 傳遞給鍵:

getPicture(e: any){
  const pictureInput=e.currentTarget.id;
  this.picture.push({[pictureInput]: e.target.files[0]}); 
}

但是,如果我想更改已經有文件的輸入中的文件,則可以使用相同的鍵添加一個新數組,並且我希望這些鍵是唯一的。

所以我的問題是:

有沒有辦法替換已經存在的鍵的值,而不是添加具有相同鍵名的新數組?

您可以使用數組索引

  • 循環時
<div v-for="(item, itemIndex) in items" :key="itemIndex">
  <img :src="item.src"/>
  <button @click=removeItem(itemIndex)>delete</button>
</div>
  • 移除項目時
  removeItem (index) {
    this.items.splice(index, 1)
  }

您可以傳遞event數據和密鑰。
更多關於這里的信息
例子:

 const app = new Vue({ el: '#app', data: { inputs: [{ file: null }, { file: null }, ] }, methods: { eventHandler(key, e) { this.inputs[key].file = e.target.files[0]; } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-for="(input, index) in inputs":key="'name-' + index"> {{index}} - {{input.file?.name}} </div> <br/> <input v-for="(input, index) in inputs" type="file":key="'picture-' + index" @change="eventHandler(index, $event)" /> </div>

最簡單的方法是在這里使用 if-else - 在此處輸入圖像描述

getPicture(e: any){
  const pictureInput = e.currentTarget.id;
  // Check if same key is already pushed
  let targetEntry = this.picture.find(e => e[pictureInput] !== undefined);
  if(targetEntry){
    // already exists REPLACE
    targetEntry[pictureInput] = e.target.files[0];
  }
  else{
    // already exists PUSH
    this.picture.push({[pictureInput]: e.target.files[0]}); 
  }
}

暫無
暫無

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

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