[Vuejs]-How to get a array index that didn't come from the DB in Vue

1👍

I think the easiest way would be to artificially introduce an ID attribute to each of your items, when you load them into the data attribute.

Something like this may be good:

new Vue({
  el: "#app",
  data: {
    pecaList: []
  },
  methods: {
    fetchData() {
      return fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(json => {
          // console.log(json)

          // creating another ID, based on the current list index
          return json.map((e, i) => {
            return { ...e,
              addedId: i
            }
          })
        })
    },
    deleteThis(id) {
      this.pecaList = this.pecaList.filter(e => e.addedId !== id)
    }
  },
  async mounted() {
    this.pecaList = await this.fetchData()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>Click on the list items to delete them one by one</h3>
  <ul>
    <li :key="peca.id" v-for="peca in pecaList" @click="deleteThis(peca.addedId)">{{peca.addedId}} {{peca.title}}</li>
  </ul>
</div>

The mockup data already has an id attribute, so I added an ID called addedId. From then on this addedId identifies your item (regardless of its index in the table or list; until you fetch another set of data or reload, or something like that), so you can use it for deletion.

Actually it’s not advised to use an items index in a list for identification – it can change (like with sorting or filtering), so whenever you want to use an ID be sure that it correctly identifies an item in all use cases.

0👍

I’ve found a way of getting what i need to be done, not like i wanted but it works, only change my b-table for a b-list-group.

It ends like this:

<b-list-group>
                <b-list-group-item v-for="(item, index) in peca.list">
                    <strong>Item: </strong>{{ index }}
                    <strong>Peça: </strong>{{ item.peca}}
                    <strong>Quantidade: </strong>{{ item.qnt}}
                    <strong>Valor Unitário: </strong>{{ item.vlUnit }}
                    <strong>Valor total: </strong>{{ item.vlTot }}

                    <b-button variant="warning" >
                        <i class="fa fa-pencil"></i>
                    </b-button>

                    <b-button variant="danger" @click="deleteTask(index)" class="mr-2">
                        <i class="fa fa-trash"></i>
                    </b-button>
                </b-list-group-item>
            </b-list-group>

Working now.

Thanks all.

Leave a comment