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

Vue.js前端使用async/await获取API数据后无法在页面展示

问题原因及修复方案

你代码里的问题出在两个核心点:

  • 全局的allRecipe是普通数组,不是Vue的响应式数据,模板无法自动感知它的变化
  • getRecipes函数里用var allRecipe = []重新声明了局部变量,直接覆盖了全局变量,导致赋值操作和模板绑定的allRecipe完全无关

修复后的完整代码

<script setup>
import { ref } from "vue";
import Axios from "axios";

// 把allRecipe改为响应式ref对象
const ingridient = ref("");
const allRecipe = ref([]);
let allData = [];

async function getRecipes() {
  const recipeApi = `https://api.edamam.com/api/recipes/v2?type=public&q=${ingridient.value}&app_id=MY_APP_ID&app_key=MY_API_KEY`;
  const recipes = await Axios.get(recipeApi);
  allData = recipes.data.hits;
  // 通过ref的value属性修改值,触发响应式更新
  allRecipe.value = allData.map((a) => a.recipe);
  console.log(allRecipe.value);
}
</script>

<template>
  <main class="flex flex-col">
    <h1 class="mt-8">Find Your Recipe</h1>
    <form @submit.prevent="getRecipes" class="m-2" action="">
      <input
        class="text-black p-1 m-1"
        type="text"
        placeholder="Enter Ingridient Name"
        v-model="ingridient"
      />
      <button
        type="submit"
        class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-3 rounded"
      >
        Search
      </button>
    </form>
    <li v-for="recipe in allRecipe" :key="recipe.id">{{ recipe.label }}</li>
  </main>
</template>

关键修改说明

  1. 将var allRecipe = []替换为const allRecipe = ref([]),把普通数组转为Vue能追踪的响应式对象
  2. 删除getRecipes函数内的var allRecipe = []声明,避免局部变量覆盖全局响应式变量
  3. 赋值时使用allRecipe.value = ...,ref对象必须通过value属性修改内部值,模板中使用时无需加.value,Vue会自动解包

修改后,当搜索获取到数据时,allRecipe的变化会被模板实时感知,就能正常渲染出菜谱列表了。

内容的提问来源于stack exchange,提问作者mrshiam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:54:21