F
F
Feato2021-06-01 22:13:36
Vue.js
Feato, 2021-06-01 22:13:36

How to create a unique key for an element in v-for?

Hello everyone, working with v-for, I noticed that it removes elements (when deleting from an array) by key :key, if you specify an index in the key, then the last element will be deleted, if the line is the last one with the same text, how can I put in :key unique identificator...

<!DOCTYPE html>
<header>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</header>

<body>
  <div id="message">
    <transition-group name="msgAnimation" tag="div">
      <div v-for="(msg, i) in messages" :key="`msg-${i}`" class="wrapper">
        <div class="wrapper__block" @click="messages.splice(i, 1)">
          {{ msg }}
        </div>
      </div>
    </transition-group>
  </div>
</body>
<style>
  #message {
    display: flex;
    flex-direction: column;
  }

  .msgAnimation-enter-active,
  .msgAnimation-leave-active {
    transition: opacity 1s;
  }

  .msgAnimation-enter,
  .msgAnimation-leave-to {
    opacity: 0;
  }

  .wrapper {
    width: 100%;
    height: 9vmin;
    margin: 1vmin;
  }

  .wrapper__block {
    background: green;
    height: 100%;
    width: 100%;
  }
</style>
<script>
  new Vue({
    el: '#message',
    data: {
      messages: [
        "привет",
        "привет",
        "123321",
        "привет",
        "32112332112sdfs",
        "привет",
        "qweewq",
        "ashjdddsa",
        "asdfddsa",
        "asggghjddsa",
        "ashddsa",
        "asjghjddsa",
        "asjddsa",
        "asdddsa",
      ],
    },
  })
</script>

</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alena Tyunyaeva, 2021-06-01
@alyonatyunyaeva

You can use index as a key only if you need to render a static list that won't change. And then, it is better not to have such a habit.
The key value must identify its element (be unique), the index does not identify the element in any way. If the values ​​of message were not exactly repeated, one could use them.
If there is no data for the key, then you need to create a calculated property and generate a unique key for each element:

computed: {
  messagesWithId() {
    return this.messages.map((el) => {
      return { message: el, key: Math.random() };
    });
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question