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

1👍

You can use the array index

  • when looping
<div v-for="(item, itemIndex) in items" :key="itemIndex">
  <img :src="item.src"/>
  <button @click=removeItem(itemIndex)>delete</button>
</div>
  • when removing item
  removeItem (index) {
    this.items.splice(index, 1)
  }

1👍

You can pass both event data and key.
More info about this here
Example:

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>

1👍

The simplest way will be to use an if-else here – enter image description here

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

Leave a comment