getElementsByClassName后循环与VueJS



我正在使用VueJS,我正在尝试循环html元素后的循环。

首先,我使用worpress API获取类别,然后按类别发布。

我的数据库中有5个类别。

我的代码中没有v-if,也许我不能循环,因为我的DOM还没有准备好我的v-for ?

我不明白为什么我不能循环我的元素。

<template>
<div id="tutos">
<div
v-for="(tuto, index) in tutos"
:id="tuto.categorie_slug"
:key="index"
class="row"
>
<div class="tutos-list"></div>
</div>
</div>
</template>
<script>
export default {
name: "Tutos",
data() {
return {
tutos: [],
};
},
methods: {
getCategories: async function () {
const categories = await this.axios.get("/categories");
return categories.data;
},
getPosts: async function (id) {
const posts = await this.axios.get("/posts?categories=" + id);
return posts.data;
},
},
mounted: async function () {
// Load datas
await this.getCategories().then((data) => {
Array.from(data).forEach((categorie) => {
if (categorie.count > 0) {
this.getPosts(categorie.id).then((posts) => {
this.tutos.push({
categorie_name: categorie.name,
categorie_slug: categorie.slug,
posts: posts,
});
});
}
});
});
// Wait For DOM
await this.$nextTick();
const tutos_list = document.getElementsByClassName("tutos-list");
// Log an HTMLCollection with 5 children
console.log(tutos_list);
// Loop Nothing
Array.from(tutos_list).forEach((list) => {
console.log(list);
});
},
};
</script>
<style lang="scss">...</style>
<<p>

更新屏幕/strong>Devtools和控制台屏幕

谢谢你:)

加载数据的部分不等待对getPosts的单独调用,并且this.getCategories().then()调用返回的承诺立即被解析,因为在其回调中没有显式的return语句返回承诺。因此,这部分代码在使用push添加任何条目之前完成。这些push调用发生在稍后执行的then回调中。你的代码没有对这些内部this.getPosts(categorie.id).then()调用返回的承诺做任何事情。

您可以使用Promise.all来等待所有getPosts的承诺,如下所示:

// Load datas
this.tutos.push(...await this.getCategories().then(data =>
Promise.all(
[...data].filter(categorie => 
categorie.count > 0
).map(async categorie => ({
categorie_name: categorie.name,
categorie_slug: categorie.slug,
posts: await this.getPosts(categorie.id)
}))
)
));

最新更新