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>
关键修改说明
- 将
var allRecipe = []替换为const allRecipe = ref([]),把普通数组转为Vue能追踪的响应式对象 - 删除
getRecipes函数内的var allRecipe = []声明,避免局部变量覆盖全局响应式变量 - 赋值时使用
allRecipe.value = ...,ref对象必须通过value属性修改内部值,模板中使用时无需加.value,Vue会自动解包
修改后,当搜索获取到数据时,allRecipe的变化会被模板实时感知,就能正常渲染出菜谱列表了。
内容的提问来源于stack exchange,提问作者mrshiam
相关产品推荐
相关产品推荐

