How to use item id from v-for list in a method of underlying component in vue3

37 Views Asked by At

I have a vue template that contains a component that is nested in a v-for list. This component has a onSave method and on save I want to update that item in the backend db. I'm having issues accessing the item id in that onSave function. The component's onSave function cannot accept inputs unfortunately. Any pointers on how I can get that item.id or index?

<div v-for="(item,index) of items" :key="index">
 <span>{{ item.id }}</span>
 <Component v-model="item.text" :componentId=generateRandomString() @onSave="onSave"/>
</div> 

<script>
  import {Component} from 'component'
  import apiService from '../service/apiService'

  export default {
  data() {
    return {
      items: null
    };
  },
  methods: {
    async loadItems() {
      try {
        const r = await apiService.getItems();
        this.items = r.data;
      }
      catch(e){
        console.log(e);
      }
    },
    onSave() {
      //Here I try to get the item.id or the item.index to find which item I need to update
    },
    generateRandomString() {
      return randomString();
    }
  }
}
</script>

1

There are 1 best solutions below

4
Alexander Nenashev On BEST ANSWER

Pass the item and the index to onSave, you can then access any properties in the item:

<Component v-model="item.text" :componentId=generateRandomString() @onSave="(v, h) => onSave(v, h, item, index)"/>

...

    onSave(v, h, item, index) {
      //Here I try to get the item.id or the item.index to find which item I need to update
    },