Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a unique key for v-for

Tags:

vue.js

please tell me how to make a unique key for v-for For example, if you use the index as a key, then the last element will always be animated. Several elements with the same text can exist at the same time. How can I implement this Math.random is unlikely to be a good problem-solving solution Can I use something like Symbol for a unique id

<!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="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: [
        "hi",
        "hi",
        "123321",
        "hi",
        "32112332112sdfs",
        "hi",
        "qweewq",
        "ashjdddsa",
        "asdfddsa",
        "asggghjddsa",
        "ashddsa",
        "asjghjddsa",
        "asjddsa",
        "asdddsa",
      ],
    },
  })
</script>

</html>
like image 787
Gorilka Avatar asked Jan 25 '26 07:01

Gorilka


1 Answers

If you have only strings you should wrap each message with object. It's more convenient way to use id instead of index in your case.

data: {
  currentId: 0,
  messages: [
    "hi",
    "hi",
    "123321",
    "hi",
  ]
},
created: function() {
  this.messages = this.messages.map(function(message) {
    return this.wrap(message)
  })
},
methods: {
  wrap: function(msg) { // make message object with unique (not random) id.
    return {
      id: ++this.currentId,
      message: msg
    }
  },
  addMessage: function(msg) {
    this.messages.push(this.wrap(msg))
  }
}

Now, each new message has own unique id, so problem with removing message by index should gone.

Then key message by id:

<div v-for="(msg, i) in messages" :key="msg.id" class="wrapper">
  <div class="wrapper__block" @click="messages.splice(i, 1)">
    {{ msg.message }}
  </div>
</div>
like image 101
Daniel Avatar answered Jan 28 '26 09:01

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!