I'm currently working on a project in Vue that uses the WP-Rest api. I'm bored of tediously nested objects when looping through objects. While I can destructure top-level objects, I'm not sure how make things like this: page.page.featuredImage.node.altText less ugly. Can anyone offer any good practices for handling nested objects within Vue loops?
<div v-for="(page, index) in pageGrid" :key="index"
>
<div v-if="page.page.featuredImage" >
<img :alt="page.page.featuredImage.node.altText"
:sizes="page.page.featuredImage.node.sizes" :srcset="page.page.featuredImage.node.srcSet" />
CodePudding user response:
Sometimes that is why to do it in the other hand you can map over your data when mounted for instant and return a new array that looks the way you want.
I am not sure how your data looks but I think you could also do something like this:
<div v-for="(page, index) in pageGrid.page" :key="index">
CodePudding user response:
As per your template code, You are having below data structure contains by pageGrid
.
[
{
page: {
featuredImage: {
node: {
altText: 'Text 1',
sizes: 'small',
srcSet: 'image src link'
}
}
}
},
{
page: {
featuredImage: {
node: {
altText: 'Text 1',
sizes: 'small',
srcSet: 'image src link'
}
}
}
},
...
...
]
To make this simple, You can move the whole node
object into a separate array with the help of Array.map() method and then it will easy to iterate in the template.
pageGrid.map(({ page }) => page.featuredImage.node);
Live Demo :
new Vue({
el: '#app',
data: {
pageGrid: [
{
page: {
featuredImage: {
node: {
altText: 'Text 1',
sizes: 'small',
srcSet: 'image 1 src link'
}
}
}
},
{
page: {
featuredImage: {
node: {
altText: 'Text 2',
sizes: 'medium',
srcSet: 'image 2 src link'
}
}
}
}
],
updatedPageGrid: []
},
mounted() {
this.updatedPageGrid = this.pageGrid.map(({ page }) => page.featuredImage.node);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(page, index) in updatedPageGrid" :key="index">
{{ page.altText }}
{{ page.sizes }}
{{ page.srcSet }}
</div>
</div>