Home > Back-end >  How to show a property from an object inside an array in Vue data during a loop defined on the Templ
How to show a property from an object inside an array in Vue data during a loop defined on the Templ

Time:03-31

My data structure:

data: {
    OBJs: [ 
        { "imageUrl": "site/image1.png", "name": "name1" }, 
        { "imageUrl": "site/image2.png", "name": "name2" }, 
        { "imageUrl": "site/image3.png", "name": "name3" }, 
        { "imageUrl": "site/image4.png", "name": "name4" }, 
        ]
}

Then on the template

<div v-for="index in OBJs.length" :key="index">
    {{OBJs[index].imageUrl}}
</div>

But I keep getting this error.

enter image description here

If I render just the OBJs[index] like this:

<div v-for="index in OBJs.length" :key="index">
    {{OBJs[index]}}
</div>

...I get the all objects!

 { "imageUrl": "site/image1.png", "name": "name1" }
 { "imageUrl": "site/image2.png", "name": "name2" } 
 { "imageUrl": "site/image3.png", "name": "name3" } 
 { "imageUrl": "site/image4.png", "name": "name4" } 

so how come are they undefined? Anybody able to help?

CodePudding user response:

you dont need to use length

just OBJs - then you will have item of array on each iteration

if you have structure like this:

export default {
    data() {
        return {
            data: {
                OBJs: [ 
                    { "imageUrl": "site/image1.png", "name": "name1" }, 
                    { "imageUrl": "site/image2.png", "name": "name2" }, 
                    { "imageUrl": "site/image3.png", "name": "name3" }, 
                    { "imageUrl": "site/image4.png", "name": "name4" }, 
                    ]
            }
        };
    }
};

UI:

<ul>
    <li v-for="item in data.OBJs" :key="item">{{item.imageUrl}}</li>
</ul>
  • Related