Vue项目中如何通过Axios获取JSON数据并填充到导航循环列表
你需要同时调整Axios响应处理逻辑和Vue响应式数据定义,具体修改如下:
1. 修改组件配置
把exhibitions定义为响应式数据,在Axios请求回调中做字段映射适配:
import axios from "axios"; export default { name: "item", data() { return { // 把exhibitions作为响应式数据,初始为空数组 exhibitions: [] }; }, mounted() { axios .get("http://localhost:8000/posts.json") .then((response) => { // Axios返回的接口实际数据存放在response.data中 const cmsData = response.data.data; // 映射CMS返回字段到你需要的exhibitions结构 this.exhibitions = cmsData.map(item => ({ name: item.title, description: "Info " + item.id, // 若CMS有对应描述字段可直接替换 href: item.url })) }); }, }
2. 模板循环渲染
在组件模板中直接使用exhibitions做循环即可:
<template> <div> <div v-for="item in exhibitions" :key="item.href"> <a :href="item.href"> <h3>{{ item.name }}</h3> <p>{{ item.description }}</p> </a> </div> </div> </template>
注意事项
- 你之前直接把response赋值给info的写法是错误的,Axios封装后的响应对象里,接口返回的原始数据存放在
response.data属性下 - 如果后续CMS新增了展览描述字段,直接替换映射逻辑里的description字段值即可
内容的提问来源于stack exchange,提问作者Oli
相关产品推荐
相关产品推荐

