VueJS 3组合式API中如何将Fetch结果赋值给其他变量?
解决Vue3中API数据赋值给weekdays变量的问题
问题背景
Vue3新手在使用Fetch API时,接口能正常返回数据并渲染到mealPrepSummary,但无法将接口数据与自定义值一同存入weekdays对象,尝试直接赋值、onActivated均无效。
核心问题分析
- 非响应式变量:原代码中
weekdays是普通JS对象,Vue无法追踪其变化,即便赋值成功,模板也不会更新。 - 赋值逻辑本身无语法错误,但因变量非响应式导致无法在模板中体现变化。
解决方案
将weekdays改为Vue响应式变量,并在异步请求完成后正确赋值:
修改后的组件代码
<script setup> import { ref, onMounted } from 'vue'; import AppDaySelector from "./AppDaySelector.vue"; import MealPrepAPI from '../api/MealPrepAPI.js'; const mealPrepSummary = ref({}); // 将weekdays声明为响应式ref变量 const weekdays = ref({}); onMounted(() => { let fetchStatus = 'S'; const loadMealPrepHP = async() => { mealPrepSummary.value = await MealPrepAPI.index(); // 确认数据返回后,赋值给weekdays的value属性 weekdays.value = { name: "something new", value: mealPrepSummary.value.api_data }; }; loadMealPrepHP().catch(error => { alert("Error fetching summary from REST API : " + error); fetchStatus = 'E'; }); }); </script> <template> <pre>{{mealPrepSummary}}</pre> <pre>{{weekdays}}</pre> <!-- 现在可正常渲染weekdays数据 --> <AppDaySelector :weekDays="mealPrepSummary.weeks"></AppDaySelector> </template>
可选:优化API代码为async/await风格
import { APISettings } from './config.js'; export default { async index(){ console.log("Inside API Call"); const response = await fetch(APISettings.baseURL + APISettings.summaryAPI + '1/', { method: 'GET', headers: APISettings.headers }); if(response.status !== 200){ throw response.status; } return response.json(); }, }
关键修改说明
- 使用
ref()将weekdays转为响应式变量,Vue会自动追踪其变化并更新模板。 - 异步请求完成后(
await确保数据已返回),通过weekdays.value赋值,这是ref变量的正确赋值方式。 - 若
mealPrepSummary.value.api_data仍为undefined,请检查接口返回的数据结构是否与预期一致,可通过console.log(mealPrepSummary.value)确认。
内容的提问来源于stack exchange,提问作者Rakshith Chengappa
相关产品推荐
相关产品推荐

