无法从 Nuxt 中的 API 访问密钥

Cannot access key from an API in Nuxt

我是 Nuxt JS 的新手。 我在 nuxt js 上阅读教程,但无法在我的页面上显示 {{planet.title}}。 但是如果我使用 {{$data}} 我会看到所有的行星。 我想要 slug 中的行星名称的标题(这里是地球,但也可以是木星或火星)

_slug.vue

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">planet.title here => {{ planet.title }}</h1>
      <pre> $data here => {{ $data }}</pre>
    </div>
  </div>
</template>

<script>
import NuxtLogo from "~/components/NuxtLogo";
export default {
  components: {NuxtLogo},
  async asyncData() {
    const planet = await fetch(
      'https://api.nuxtjs.dev/planets'
    ).then((res) => res.json())
    return { planet }
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

我的网页:

这是改进代码的方法

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">planet.title here => {{ planet.title }}</h1>
      <pre> $data here => {{ $data }}</pre>
      <section>
        <div v-for="planet in planets" :key="planet.slug">
            <p>Title of my planet: {{ planet.title }}</p>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
export default {
  async asyncData() {
    const call = await fetch('https://api.nuxtjs.dev/planets')
    const planets = await call.json()
    return { planets }
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

PS: 不要忘记 :key.


API returns 一个数组。如果要访问第一个星球的title,使用planet[0].title.

你当然也可以用 v-for 遍历整个数组。更多信息在这里:https://vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for

看起来 Planet 是一个数组,因此您需要遍历该数组,然后打印您想要的数组值尝试使用

<ul>
  <li v-for="item in planets">
    {{ item.title}}
  </li>
</ul>

planet 正如您在显示变量时看到的那样 $data 是一个行星数组。

您应该将 planet 变量重命名为 planets 以便更好地表示其内容。

要显示行星,您需要从 planets 数组中获取它:

<template>
  <div class="container">
    <div>
      <NuxtLogo />
      <h1 class="title">earth.title here => {{ earth.title }}</h1>
    </div>
  </div>
</template>

<script>
import NuxtLogo from "~/components/NuxtLogo";
export default {
  components: {NuxtLogo},
  async asyncData() {
    const planets = await fetch('https://api.nuxtjs.dev/planets')
        .then((res) => res.json())

    const earth = planets[0];

    return { planets, earth }
  }
}
</script>