Vue3+Axios无需循环展示数据:{{heros.title}}无法生效的解决方法
问题:Vue3中无法直接通过
{{heros.title}}访问API返回的数据 问题背景
我在Vue3项目中想直接打印API返回的数据,不想用循环,但使用{{heros.title}}无法生效,以下是相关信息:
Axios API响应
[ {id: 2, name: "sub_title", value: "The Best Developer Team", created_at: null, updated_at: null}, {id: 3, name: "title", value: "We Are the Brilliants Creative Secure Maintain Build in Terms of website Development", created_at: null, updated_at: null}, {id: 4, name: "description", value: "End-to-end payments and website management in a single solution. Meet the right team to help realize.", created_at: null, updated_at: null}, {id: 5, name: "button_text", value: "Get Started", created_at: null, updated_at: null}, {id: 6, name: "video_text", value: "How We Works", created_at: null, updated_at: null}, {id: 7, name: "video_url", value: "#video", created_at: null, updated_at: null}, {id: 8, name: "url", value: "/frontend/assets/img/hero/1667138531.png", created_at: null, updated_at: null}, {id: 9, name: "image", value: "1667138531.png", created_at: null, updated_at: null} ]
Vue组件代码
axios.get('/api/sites/hero').then(response => { this.heros = response.data.map(obj => { let hero_data = {}; hero_data[obj.name] = obj.value; console.log(hero_data); return hero_data; }) }).catch(function (handleError) { console.log("Error: ", handleError); }, []);
控制台输出
{sub_title: 'The Best Developer Team'} {title: 'We Are the Brilliants Creative Secure Maintain Build in Terms of website Development'} {description: 'End-to-end payments and website management in a single solution. Meet the right team to help realize.'} {button_text: 'Get Started'} {video_text: 'How We Works'} {video_url: '#video'} {url: '/frontend/assets/img/hero/1667138531.png'} {image: '1667138531.png'}
问题原因
当前用map处理后,heros是一个对象数组,结构为[{sub_title: ...}, {title: ...}, ...],每个元素都是单独的键值对对象,因此heros.title找不到对应属性,无法渲染。
解决方案
把数组转换成单个对象,用reduce代替map合并所有键值对:
axios.get('/api/sites/hero').then(response => { this.heros = response.data.reduce((acc, obj) => { acc[obj.name] = obj.value; return acc; }, {}) // 初始值设为空对象 }).catch(function (handleError) { console.log("Error: ", handleError); });
处理后heros的结构变为:
{ sub_title: 'The Best Developer Team', title: 'We Are the Brilliants Creative Secure Maintain Build in Terms of website Development', description: 'End-to-end payments and website management in a single solution. Meet the right team to help realize.', button_text: 'Get Started', video_text: 'How We Works', video_url: '#video', url: '/frontend/assets/img/hero/1667138531.png', image: '1667138531.png' }
此时就能在模板中正常使用{{heros.title}}、{{heros.sub_title}}等直接访问数据了。
内容的提问来源于stack exchange,提问作者Happy Arif
相关产品推荐
相关产品推荐

