Vue3项目中setup先返回空sections数组,接口加载数据后页面渲染异常问题求助
解决Vue3中Axios获取数据后模板不渲染的问题
我看了你的代码,发现几个关键问题导致模板无法正确渲染接口返回的数据,咱们一步步来修复:
1. 修正模板中的拼写和条件判断错误
这是最核心的问题,你的模板里有两处明显错误:
- 你用了
v-if="state.length > 0",但state是一个包含sections数组的对象,state.length永远是undefined,所以这个条件永远不成立,就算接口返回了数据也不会显示内容。 - 循环的时候写的是
state.section(单数),但你的响应式数据里是state.sections(复数),拼写错误导致循环找不到正确的数组。
修正后的模板代码:
<div v-if="state.sections.length > 0 "> <div class="__course-sub-section" v-for="(section, index) in state.sections" :key="index"> <div><input type="text" placeholder="Enter Section Title" v-model="section.section_title" class="section-title form-control x_focus"></div> <div class="__upload-section d-flex justify-content-between align-items-center" v-for="(sub_section, idx) in section.sub_state" :key="idx"> <div class="d-flex"> <input type="text" placeholder="Enter Sub Section Title" v-model="sub_section.sub_section_title" class="section-title form-control x_focus"> <div class="__choose"> <label for=""> <div> <input type="file" @change="uploadFile( $event, index, idx )" name="" id=""> Upload File </div> <img src="@/assets/images/upload.png" alt=""> </label> </div> </div> <div class="__sub-section-image"> <div class="placeholders"> <div v-if="sub_section.subSectionAdded"> <img :src="sub_section.imageURL" alt=""> </div> <div v-if="!sub_section.subSectionAdded"> <img src="@/assets/images/upload.png" alt=""> </div> </div> </div> <button @click="addSubSection(index)" class="app_button primary_btn d-flex mt-4"> Add Sub Section </button> </div> </div> </div>
2. 优化初始状态处理(可选)
你当前的初始state.sections包含一个默认的section项,如果你希望在接口返回数据前不显示任何占位内容,可以把初始值改成空数组,这样体验更合理:
let state = reactive({ sections: [] });
如果需要保留初始的空section作为添加入口,那保持原来的初始值也没问题,接口返回数据后会自动替换掉这个默认项。
3. 确认id变量的有效性
注意你调用Course.getSectionAndSubsections时用到的id参数,要确保它已经正确获取(比如从组件props、路由参数或者其他地方拿到),如果id是undefined或者无效值,接口请求会失败,自然也不会返回数据。
为什么之前的代码不生效?
- 模板的条件判断
state.length > 0永远为假,导致整个内容块被隐藏; - 循环的数据源拼写错误,找不到
state.section这个属性; - 这两个问题叠加,就算接口成功返回了数据,模板也无法正确渲染它们。
修复这些问题后,当Axios请求完成并给state.sections赋值时,Vue的响应式系统会自动触发模板更新,就能正确展示服务器返回的数据了。
内容的提问来源于stack exchange,提问作者etranz
相关产品推荐
相关产品推荐

