undefined id when trying to add an id dinamically in Vue.js

This a simple to-do list and I am trying to add an id in each <li> that is rendered. Each id should be named different (obviously) but similar name: "id0","id1","id2"...etc The number comes from the directive v-for="i in items"

I do it like this:

<li :id="`id${i.id}`" v-for="i in items" :key="`id${i.id}`">

Complete code:

 <ul class="item-list-ul">
        <li :id="`id${i.id}`" v-for="i in items" :key="`id${i.id}`">{{ i }}
          <div class="item-butons">
            <b-button class="done-btn" @click="strikeItem(i)" size="sm" variant="outline-dark">DONE!</b-button>
            <b-button class="delete-btn" @click="deleteItem(i)" size="sm"  variant="warning">Delete</b-button>

My items array:

data () {
      return {
          items: ["five", "<li>", "should","be","rendered"]

But when I check in the console the names of the new dinamically created id´s of the <li> they just appear idundefined when in the case of having for example 3 <li> they should appear like this:


However in the console there aren´t any errors. It seems that the vue-html simply does not read a number in ${i.id} but just undefined. Why?

1 answer

  • answered 2019-10-15 15:39 David Weldon

    If items is just an array of strings, then there is no id property available. The standard idiom in this case is to use the index like so:

    <li v-for="(i, index) in items" :id="`id${index}`" :key="index">

    Alternatively, you could reshape your data to have ids like:

    [{ id: 0, text: 'foo' }, { id: 1, text: 'bar' }, { id: 2, text: 'baz' }]

    That could be done as part of a computed property, for example. Note this would also require a few changes to your template.