Nuxt调用API后无法访问返回数据的key,无法渲染planet.title问题求助
问题原因
- 你调用的
https://api.nuxtjs.dev/planets接口返回的是包含所有行星数据的数组,不是对应slug的单个行星对象,你直接将数组赋值给planet变量,数组本身不存在title属性,因此渲染为空。 - 你没有在
asyncData中获取当前页面的slug参数,无法筛选出匹配的行星数据。
解决方法
修改_slug.vue的script部分代码,在asyncData中接收页面参数,拿到数组后筛选出和当前slug匹配的单条行星数据即可,完整修改后的代码如下:
<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({ params }) { // 拿到所有行星数组 const planets = await fetch( 'https://api.nuxtjs.dev/planets' ).then((res) => res.json()) // 筛选和当前页面slug匹配的单条行星数据 const planet = planets.find(item => item.slug === params.slug) return { planet } } } </script> <style> .container { margin: 0 auto; min-height: 100vh; display: flex; justify-content: center; align-items: center; } </style>
修改后访问/earth、/mars等路径时,就会自动渲染对应行星的标题内容。
内容的提问来源于stack exchange,提问作者Nolan Rassant
相关产品推荐
相关产品推荐

