从axios调用invue js返回值

时间:2018-08-01 12:50:07

标签: vue.js promise async-await axios

对于我国家列表中的每个国家,我需要使用axios进行api调用以获取长度:

<div v-for="country in countries" :key="'loop1' + i.id" class="pays__line" >
  <div>{{ matchCount(i.id) }}</div>
</div>

在我的脚本中,我现在有了它,但是我的方法matchCount()不会返回任何内容(但是console.log返回控制台的长度):

<script>
export default {
  props: {
    countries: {
      type: Array,
      required: true
    }
  },
  data() {
    return {};
  },
  methods: {
    matchCount(id) {
      this.$axios
        .get(
          `https://api.com/federation/${id}`
        )
        .then(response => {
          console.log("res axios", response.data.length);
          return response.data.length;
        })
        .catch(function(error) {
          console.log(error);
        });
     }
   }
  };
</script>

如何每次都返回值?

我也尝试过这种方法,但是再次可以通过日志,但是组件中什么也没返回:

matchCount: async function(id) {
  var pop = await this.$axios.get(
    `https://api.com/${id}`
  );
  console.log(pop.data.length.toString());
  return pop.data.length.toString();
}

0 个答案:

没有答案