提前谢谢你。
因此,我通过API获取博客类别列表,并使用v-for将其呈现在列表中。
我还需要获取每个类别中的博客数量,并将它们放在类别旁边。
但问题是我正在调用一个调用api的方法。
<li v-for="item in sidebar" :key="item.identifier">
<nuxt-link
tag="a"
:to="{
name: 'blog-page',
query: { category: item.identifier }
}"
>{{ $localize(item.translations).title }}
{{ getBlogCount(item.identifier) }}
</nuxt-link>
</li>您知道它已经显示的示例是Animals [Object Promise]
methods: {
async getBlogCount(identifier) {
axios
.get(
"https://example.com/posts?fields=created_at&filter[category.category_id.identifier]=" +
identifier +
"&meta=*"
)
.then(count => {
return count.data.meta.result_count;
});
}
}处理这类事情的最好方法是什么?
发布于 2020-07-20 13:50:50
我建议在脚本中处理,而不是HTML模板。
您可以做的是,根据侧栏初始化的时间(可能在挂载的钩子中),调用getBlogCount方法来获取侧栏中每个项目的博客计数,并将其存储在数组或对象中(或者作为同一侧栏项目对象的单独键值对),然后使用该数据结构在模板中显示计数值。
假设侧边栏填充在挂载的钩子中,并且它是一个对象数组,您可以执行以下操作:
<template>
<li v-for="item in sidebar" :key="item.identifier">
<nuxt-link
tag="a"
:to="{
name: 'blog-page',
query: { category: item.identifier }
}"
>{{ $localize(item.translations).title }}
{{ item.blogCount }}
</nuxt-link>
</li>
</template>
<script>
mounted () {
// after the sidebar is populated
this.sidebar = this.sidebar.map(async item => {
item.blogCount = await this.getBlogCount(item.identifier)
return item
})
}
</script>希望这能帮到你
发布于 2020-07-20 13:54:55
最好在挂载或创建的钩子中调用异步方法,并将结果设置为data,然后在模板中使用该数据。
https://stackoverflow.com/questions/62989143
复制相似问题