Skip to content

Instantly share code, notes, and snippets.

@Mykola-Veryha
Created June 9, 2024 11:26
Show Gist options
  • Save Mykola-Veryha/c7087b80d8501dd411ca8ade2cfba809 to your computer and use it in GitHub Desktop.
Save Mykola-Veryha/c7087b80d8501dd411ca8ade2cfba809 to your computer and use it in GitHub Desktop.
Preparation Vue Certeficate

Why not always use the index as the key in a vue.js for loop?

Because arrays are mutable. The index of any given item can and will change if items are added to or removed from the array. You want your key to be a unique value identifying only your unique component. A primary key that you create is always better than using an index. Here is an example. (https://stackoverflow.com/questions/44531510/why-not-always-use-the-index-as-the-key-in-a-vue-js-for-loop)

https://playcode.io/1899965

<template>
  <li>Internal: {{ internalValue }} Prop: {{ value }}</li>
</template>

<script>
export default {
  props: ["value"],
  data() {
    return {
      internalValue: this.value,
    };
  },
};
</script>

<style scoped>
/* Add any component-specific styles here */
</style>
<template>
  <div id="app">
    {{ items }}
    <ul>
      <Item v-for="(value, i) in items" :value="value" :key="value"></Item>
    </ul>
    <button @click="addValue">Add Value</button>
    <ul>
      <Item v-for="(value, i) in items" :value="value" :key="i"></Item>
    </ul>
  </div>
</template>

<script>
import Item from "./Item.vue";

export default {
  components: {
    Item,
  },
  data() {
    return {
      items: [1, 2, 3, 4, 5],
    };
  },
  methods: {
    addValue() {
      this.items.splice(this.items.length / 2, 0, this.items.length + 1);
    },
  },
};
</script>

<style>
/* Add any global styles here */
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment