I'm pretty new on Nuxt JS. I fillow tutorials on nuxt js, and I can't show a {{planet.title}} on my page. But if I use {{$data}} i see all the planets. I want the title of the planet's name I have in the slug (here it's earth but it can be jupiter or mars)
_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>
My Web Page :
This is how you can improve your code
<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: don't forget the :key.
The API returns an array. If you want to access the title of the first planet, use planet[0].title.
You can also of course loop on the whole array with v-for. More info here: https://vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for
planet as you can see when you display the variable $data is an a array of planets.
You should rename planet variable to planets so it represents better its contents.
To display a planet, you need to get a it from the planets array:
<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>
Looks like Planet is an array so you need to iterate over the array and then print the values that you want for that array try with
<ul>
<li v-for="item in planets">
{{ item.title}}
</li>
</ul>