I am currently working on a Vue component that receives an array of 'items' from its parent.
These items are then categorized with two items in each category:
computed: {
// sort items into categories
glass: function() {
return this.items.filter(i => i.category === "glass").slice(0, 2);
},
ceramics:
// etc...
To pass these categorized items as props to another component, I need to place both items in categories.items
:
data() {
return {
categories: [
{ name: "Glass", sort: "glass", items: {} },
{ name: "Ceramics", sort: "ceramics", items: {} },
{ name: "Brass", sort: "brass", items: {} },
{ name: "Books/Comics", sort: "books", items: {} },
{ name: "Collectibles", sort: "collectibles", items: {} },
{ name: "Pictures", sort: "pictures", items: {} },
{ name: "Other", sort: "other", items: {} }
]
};
},
However, I'm facing issues when passing the data through various lifecycle hooks. The 'items' are fetched using an Axios GET request from the parent component:
methods: {
fetchItems() {
let uri = "http://localhost:8000/api/items";
this.axios.get(uri).then(response => {
// randomize response
for (let i = response.data.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[response.data[i], response.data[j]] = [
response.data[j],
response.data[i]
];
}
this.items = response.data;
});
}
},
When passing props to the child component, it works fine but may be affected by the nature of the asynchronous GET request:
<div class="items-container" v-for="category in categories" :key="category.name">
<router-link :to="'category.link'" class="category-names-home-link">
<h2 class="category-names-home">{{ category.name }}</h2>
</router-link>
<router-link :to="'category.link'" class="home-view-all" @mouseover.native="expand" @mouseout.native="revert">View All...</router-link>
<div class="items">
<!-- Pass to child component as props: -->
<SubItem :item="categories.items" />
<SubItem :item="categories.items" />
</div>
</div>