Vue3调用Strapi API刷新页面出现TypeError问题求助
问题解决:Vue3刷新页面时Strapi接口数据访问报错
问题原因
刷新页面时,组件会先完成初始渲染,但此时axios的异步请求还未返回数据,component_1还是初始的空数组,直接访问component_1.imgBg.data.attributes.url会因属性不存在抛出TypeError。而保存文件时属于热更新,数据可能已缓存,因此不会触发报错。
解决方法
1. 修正初始值类型
接口返回的component_1是对象而非数组,将初始值改为空对象:
<script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; const page = ref([]); // 把初始数组改为空对象 const component_1 = ref({}); async function fetchPage() { await axios.get('http://localhost:1337/api/landing-page?populate=deep').then((response) => { console.log(response.data.data.attributes.PageContent[0].imgBg.data.attributes.url); component_1.value = response.data.data.attributes.PageContent[0]; }); } onMounted(async () => { await fetchPage(); }); </script>
2. 使用可选链操作符(推荐)
在模板中用?.访问嵌套属性,即使中间某个属性未定义,也不会抛出错误:
<h2>{{ component_1.imgBg?.data?.attributes?.url }}</h2>
3. 条件渲染确保数据存在
给渲染元素添加v-if,确认数据加载完成后再渲染:
<h2 v-if="component_1.imgBg">{{ component_1.imgBg.data.attributes.url }}</h2>
内容的提问来源于stack exchange,提问作者Inês
相关产品推荐
相关产品推荐

