【问题标题】:How to get API using axios in nuxt.js?如何在 nuxt.js 中使用 axios 获取 API?
【发布时间】:2020-07-17 07:40:59
【问题描述】:

我想获取 API 信息并设置数据表。 但是我的代码有错误。 错误消息在控制台下方。

属性或方法“items”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。

请有人给我建议?

而且我的英语不好,所以请有人帮助我的问题正确英语。

<template>
  <v-app>
    <v-data-table dense :headers="headers" :item="items" class="elevation-1"></v-data-table>
  </v-app>
</template>

<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
import axios from "axios";

@Component
export default class AxiosPractice extends Vue {
  items: object[] = [];

  headers = [
    { text: "id", value: "postId" },
    { text: "name", value: "name" },
    { text: "email", value: "email" }
  ];
  async mounted() {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/posts/1/comments"
    );
    this.itmes = response.data.map((comment:any) => ({
      postId: comment.postId,
      email: comment.email,
      name: comment.name
    }));
  }
}
</script>

【问题讨论】:

  • 尽量不要将awaitthen() 混在一起,这只会让事情变得混乱

标签: typescript vue.js nuxt.js


【解决方案1】:

我认为response 是一个包含属性data 的对象(参见docs),它(在这种情况下)包含一个对象数组。 假设你想为items 中的每条评论保存 postId、email 和 name,你可以试试这个:

const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1/comments');

this.items = response.data.map(comment => ({
  postId: comment.postId,
  email: comment.email,
  name: comment.name,
}));

【讨论】:

  • 感谢您的回答。我试过你的代码,但有错误。
  • itmes:⇒“AxiosPractice”类型上不存在属性“items”。你是说'itmes'
  • comment⇒参数 'comment' 隐含了一个 'any' 类型。
  • 我真的理解你的解释,我真的很感激。你能解释一下error.please吗??
  • 您在项目中有错字:itmes:object
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 2020-05-02
  • 2020-06-11
  • 1970-01-01
  • 2023-03-25
  • 2021-09-05
  • 2022-06-15
  • 2017-08-27
相关资源
最近更新 更多