如何在Axios请求完成后再渲染Vue组件?
问题解决思路
核心错误:ref变量赋值方式错误
你代码里的关键问题是直接覆盖了ref创建的变量,而不是修改它的.value属性,导致响应式失效——请求返回后数据更新了,但视图不会同步刷新。
正确的赋值方式是通过.value修改ref包装的变量:
onMounted(() => { axios.get('/api/projects').then(res => { // 必须通过.value修改ref变量 projects.value = res.data.data; }); });
优化体验:处理异步请求的状态
组件在请求返回前渲染是正常的(Axios请求是异步操作),你可以添加加载状态、空数据提示,避免用户看到空白或异常:
修改后的完整代码
<template> <div class="p-4 m-4 bg-white rounded flex flex-col"> <div> <h1 class="text-2xl text-gray-700">Projects</h1> </div> <div class="justify-center flex"> <!-- 加载状态提示 --> <div v-if="isLoading" class="py-8">加载中...</div> <!-- 空数据提示 --> <div v-else-if="projects.length === 0" class="py-8">暂无项目数据</div> <!-- 数据表格 --> <table v-else class="table-auto justify-center"> <thead> <tr> <th class="border px-4 py-2">ID</th> <th class="border px-4 py-2">Name</th> <th class="border px-4 py-2">Tasks</th> <th class="border px-4 py-2">Actions</th> </tr> </thead> <tbody> <tr v-for="project in projects" :key="project.id"> <td>{{project.id}}</td> <td>{{project.name}}</td> <td>{{project.task_count}}</td> <td>Actions</td> </tr> </tbody> </table> </div> </div> </template> <script setup> import { onMounted, ref } from 'vue'; // 初始化为空数组,避免v-for遍历null/undefined时报错 let projects = ref([]); // 加载状态变量 const isLoading = ref(true); onMounted(() => { axios.get('/api/projects') .then(res => { projects.value = res.data.data; }) .catch(err => { console.error('项目列表请求失败:', err); }) .finally(() => { // 请求完成后结束加载状态 isLoading.value = false; }); }); </script>
额外说明
- 把
projects初始化为空数组[],而非null,可以避免v-for遍历空值时的潜在报错。 - 添加
catch捕获请求错误,方便开发阶段调试问题。 - 使用
finally确保无论请求成功或失败,都能结束加载状态,避免用户一直看到加载提示。
内容的提问来源于stack exchange,提问作者googerdi
相关产品推荐
相关产品推荐

