Search code examples
methodsvue.jscomputed-propertiesv-for

Get index within v-for using computed or method


I was wondering if it is possible in vue to get the index of an object array directly within the v-for in and pass this value to a computed property or a method, similar to this here, or even a computed property

<div v-for="(object, index) in objects(index)"></div> 

methods: {
   objects(index){
    const categoryId = Object.keys(this.data);
    return this.data[categoryId[index]].extras;
   } 
}

I need to have the index as it is more convenient for me to return the correct value based on defined key, is there some way to achieve this?


Solution

  • Transform your data using a computed value and loop over that. I am not sure what your this.data looks like, but something like this should work (tweak it to suit your needs):

    <div v-for="object in computed_objects"></div> 
    
    computed: {
       computed_objects(){
        return Object.keys(this.data).map(categoryId => this.data[categoryId].extras)
       } 
    }