1

先感谢您。

所以我通过获取博客类别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;
        });
    }
  }

处理这种事情的最佳方法是什么?

4

2 回答 2

3

您最好在挂载或创建的钩子中调用异步方法,并将结果设置为数据,然后在模板中使用该数据。

于 2020-07-20T05:54:54.557 回答
0

我建议在脚本中处理这个,而不是 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-20T05:50:49.570 回答