我有一个Vue组件,它从其父级接收一个“项目”数组。
我将它们分类,每个类别中有两个“项目”:
NUMBER(15,12)
我需要将两个项目都放在computed: {
// sort items into categories
glass: function() {
return this.items.filter(i => i.category === "glass").slice(0, 2);
},
ceramics:
// etc...
中,然后将它们作为道具传递给另一个组件:
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: {} }
]
};
},
或created
时,没有任何传递,当我使用mounted
或beforeDestroy
和destroy
时,结果运行良好,但是,它们在退出页面时没有用。
“项目”来自Axios GET请求,这可能是为什么吗?
从父组件获取请求:
console.log
将道具传递给子组件:
methods: {
fetchItems() {
// items request
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;
});
}
},
答案 0 :(得分:1)
computed: {
filtered() {
if (!this.items) return null;
const filtered = {};
this.items.forEach(item => {
if (filtered[item.category]) {
filtered[item.category].push(item);
} else {
filtered[item.category] = [item];
}
});
return filtered;
}
}
结果:
{
'Glass': [ ... ],
'Ceramic': [ ... ]
...
}
在模板中:
<div>
<div v-for="category in categories" :key="category.name">
<div class="items" v-for="item in filtered[category.name]">
<SubItem :item="item" />
</div>
</div>
</div>
您可以在父级中使用v-if
来防止在加载数据之前显示任何内容:
<display v-if="items" :items="items"></display>
这里是demo