axios 在 vuejs 和 nuxt 的方法中调用

axios call in a method with vuejs and nuxt

对于我的国家列表中的每个国家,我需要使用 axios 进行 api 调用以获得另一个值,这里是 y 分量:

<template>
  <div>
    <div v-for="(country, i) in countries" :key="i">
      <div>{{ county[i.id].count }}</div>
    </div>
  </div>
</template>

在我的脚本中,我调用我的方法 matchCount on mounted 并将值存储在我的县数据对象中:

<script>
export default {
  props: {
   countries: {
    type: Array,
    required: true
    }
  },
 data() {
  return {
    county = {}
  };
 },
 mounted() {
  this.matchCount();
 },
 methods: {
   matchCount() {
     var paysCount = this.pays;
     paysCount.forEach(item => {
       this.$axios
        .get(
          `https://api.com/federation/}/${item.id}/`
        )
        .then(response => {
          this.county[item.id] = {};
          this.county[item.id].count = response.data.length.toString();
        });
     });
   }
  }
};
</script>

我收到此错误 "TypeError: Cannot read property 'count' of undefined",我应该如何调用此方法?

county[item.id].count 是异步设置的,渲染组件时可能不可用。您可以添加安全检查:

<template>
  <div>
    <div v-for="(country, i) in countries" :key="i">
      <div v-if="county[i.id]">{{ county[i.id].count }}</div>
      <div v-else>Loading...</div>
    </div>
  </div>
</template>

你似乎有 reactivity problem:

this.$axios
    .get(
      `https://api.com/federation/}/${item.id}/`
    )
    .then(response => {
      this.$set(this.county, item.id, {count: response.data.length.toString())
    });

您会发现在 HTML 模板中使用以下语法很有用 {{variable[key] && variable[key].value}}

在您的特定情况下,它将是:

<template>
  <div>
    <div v-for="(country, i) in countries" :key="i">
      <div>{{ county[i.id] && county[i.id].count }}</div>
    </div>
  </div>
</template>

它的作用,本质上是验证键 i.id 是否存在于 county 数组中。如果没有,它不会抛出关于丢失对象/键的错误。

您也可以在使用对象时使用此语法,如下所示:

<div v-text="house.dog && house.dog.name" ></div>

如果 doghouse 对象中,那么它将显示 dog's 名称。

编辑:

在函数中添加this.$forceUpdate();

matchCount() {
 var paysCount = this.pays;
 paysCount.forEach(item => {
   this.$axios
    .get(
      `https://api.com/federation/}/${item.id}/`
    )
    .then(response => {
      this.county[item.id] = {};
      this.county[item.id].count = response.data.length.toString();
      this.$forceUpdate();
    });
 });
}