Vue.js 问题:点击Logs标签加载后端数据后如何渲染组件列表?
解决Vue标签页点击后加载数据不渲染的问题
核心问题:变量名拼写错误
你定义的响应式数据是auditLogs: [],但在handleClick和fetchAuditLogs方法里错误地写成了audioLogs(混淆了“audit(审计)”和“audio(音频)”),导致后端返回的数据没有正确赋值到目标数组,组件自然无法渲染列表。
修正后的代码
方法部分:
handleClick(tab, event) { // 修正变量名:audioLogs → auditLogs if(tab.name === 'audit-logs' && this.auditLogs.length === 0) { this.fetchAuditLogs(); } }, fetchAuditLogs() { axios.get(route('api.questions.logs', { 'model':'question', 'model_id': this.$route.params.questionId })) .then((response) => { // 同样修正变量名 this.auditLogs = response.data.outcome.data; }); },
模板部分(添加key优化):
Vue的v-for需要唯一key来追踪元素,避免渲染异常,建议补充:
<el-tab-pane :label="Logs" name="audit-logs"> <QuestionAuditLogComponent v-for="log in auditLogs" :key="log.id" :audit-log="log" ></QuestionAuditLogComponent> </el-tab-pane>
额外优化:防止重复请求
可以添加加载状态变量,避免用户多次点击标签页触发重复接口请求:
- 在data中定义:
data() { return { auditLogs: [], currentTab: '', isLoadingLogs: false // 新增加载状态 } }
- 修改方法:
handleClick(tab, event) { if(tab.name === 'audit-logs' && this.auditLogs.length === 0 && !this.isLoadingLogs) { this.fetchAuditLogs(); } }, fetchAuditLogs() { this.isLoadingLogs = true; axios.get(route('api.questions.logs', { 'model':'question', 'model_id': this.$route.params.questionId })) .then((response) => { this.auditLogs = response.data.outcome.data; }) .finally(() => { this.isLoadingLogs = false; }); },
内容的提问来源于stack exchange,提问作者M a m a D
相关产品推荐
相关产品推荐

