如何在Vue组件模板中使用Axios获取的数据?
解决方案
你的问题出在给Blog组件传递数据的方式上:当前你写的:articles="{ articles }"会把请求到的数组包装成一个{ articles: [...你的数组] }的对象,但你的Blog组件应该是期望直接接收数组(毕竟静态数组能正常运行)。
修复步骤
直接修改模板中传递props的代码,去掉多余的对象包装:
<template> <div class="content"> <h1 class="center">Nyheter</h1> <div class="news-content"> {{ articles }} <Blog :articles="articles" /> </div> </div> </template>
额外优化建议
- 提前初始化数据:在组件的
data中提前把articles初始化为空数组,避免数据加载完成前模板出现undefined的提示:
data() { return { articles: [] } }
- 检查子组件props定义:确认
Blog组件的props是按数组类型接收的,比如:
props: { articles: { type: Array, required: true, default: () => [] } }
这样修改后,axios请求到的数据就能正确传递给Blog组件并正常渲染了。
内容的提问来源于stack exchange,提问作者Anders Kleimark
相关产品推荐
相关产品推荐

