Vue.js调用RapidAPI的MyAnimeList接口无法显示标题求助
解决Vue.js中MyAnimeList克隆项目的数据渲染问题
核心问题:卡片组件的属性访问路径错误
页面无内容的主要原因是卡片组件对传入数据的访问路径错误。父组件通过v-for遍历的anime是API返回data.contents中的单个动画对象,而卡片组件错误地使用了animeInfo.animes.title,正确的访问路径应为animeInfo.title。
修复步骤
1. 修改卡片组件模板
将卡片组件的<h2>标签内容修正:
<template> <div> <h2>{{ animeInfo.title }}</h2> </div> </template>
2. 添加调试日志验证数据结构
在fetch的回调中新增日志,确认API返回的数据结构是否符合预期:
fetch(url, options) .then((response) => response.json()) .then((data) => { console.log('API返回数据:', data); // 调试用日志 animes.value = data.contents; }) .catch((error) => console.error('获取数据失败:', error))
打开浏览器控制台检查:
- 是否有API密钥无效、跨域等报错信息
data.contents是否为包含动画对象的数组- 每个动画对象是否存在
title和id字段
3. 额外检查项
- 确认你的RapidAPI密钥已授权访问当前使用的接口
- 若
anime.id不存在,可将v-for的key改为index或其他唯一标识字段
修复后完整代码示例
页面组件(仅添加调试日志)
<template> <div class="topAnime"> <h1>Top anime</h1> <div class="card"> <CardComponent v-for="anime in animes" :key="anime.id" :animeInfo="anime"/> </div> </div> </template> <script setup> import CardComponent from "../components/CardComponent.vue"; import { onMounted, ref } from "vue"; const animes = ref([]) onMounted(() => { const url = 'https://anime-db.p.rapidapi.com/anime?page=1&size=10'; const options = { method: 'GET', headers: { 'x-rapidapi-key': '5ba5251626msh61775206ad42e40p1981dbjsn73e0574f7887', 'x-rapidapi-host': 'anime-db.p.rapidapi.com' } } fetch(url, options) .then((response) => response.json()) .then((data) => { console.log('API返回数据:', data); animes.value = data.contents; }) .catch((error) => console.error('获取数据失败:', error)) }) </script> <style scoped> a { color: black; text-decoration: none; } </style>
卡片组件(修正后)
<template> <div> <h2>{{ animeInfo.title }}</h2> </div> </template> <script setup> defineProps({ animeInfo: Object }) </script> <style scoped> </style>
内容的提问来源于stack exchange,提问作者Vipe
相关产品推荐
相关产品推荐

