You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS 3组合式API中如何将Fetch结果赋值给其他变量?

解决Vue3中API数据赋值给weekdays变量的问题

问题背景

Vue3新手在使用Fetch API时,接口能正常返回数据并渲染到mealPrepSummary,但无法将接口数据与自定义值一同存入weekdays对象,尝试直接赋值、onActivated均无效。

核心问题分析

  1. 非响应式变量:原代码中weekdays是普通JS对象,Vue无法追踪其变化,即便赋值成功,模板也不会更新。
  2. 赋值逻辑本身无语法错误,但因变量非响应式导致无法在模板中体现变化。

解决方案

将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:17:48