【问题标题】:How do I create unique keys/replace its value with array.push?如何创建唯一键/用 array.push 替换其值?
【发布时间】:2021-05-28 19:42:43
【问题描述】:

我有动态生成的输入,我需要将它们添加到一个数组中。

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]}); 
}

但是,如果我想更改已有文件的输入中的文件,则可以使用相同的键添加一个新数组,并且我希望这些键是唯一的。

所以我的问题是:

有没有办法替换已经存在的键的值,而不是添加一个具有相同键名的新数组?

【问题讨论】:

  • 使用 Map() 而不是使用对象数组,它有一个可迭代的键值结构
  • 我会试试的。谢谢。
  • 是的,我试过Map() 并且效果很好!谢谢。

标签: javascript arrays typescript vue.js


【解决方案1】:

最简单的方法是在这里使用 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]}); 
  }
}

【讨论】:

    【解决方案2】:

    可以使用数组索引

    • 循环时
    <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)
      }
    

    【讨论】:

    • 谢谢。这不是我想要的,但我会投票,因为它可能有用。
    【解决方案3】:

    您可以同时传递 event 数据和密钥。
    有关此的更多信息here
    示例:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2014-11-22
      • 1970-01-01
      • 2016-04-12
      相关资源
      最近更新 更多