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

Vue3组合式API中如何在组件创建阶段调用API?

问题原因与解决方案

核心问题

你定义的pizzas是普通变量,不具备响应式特性。Vue 3组合式API中,只有通过ref/reactive创建的变量,才能在值变化时自动触发模板更新。另外你同时混用await和.then(),写法冗余且易出错。

修复代码

<template>
  <div>
    <!-- 加载状态提示 -->
    <div v-if="pizzas.length === 0" class="text-center py-4">
      加载中...
    </div>
    <div 
      class="row mb-2 border-top border-bottom" 
      v-for="pizza in pizzas" 
      :key="pizza.id" <!-- 改用唯一ID作为key,避免重复渲染问题 -->
    >
      <div class="col-sm-2">
        <img alt="Vue logo" src="../assets/logo.png" style="height: 100px; width: 135px;">
      </div>
      <div class="col-sm-2 mt-4">
        {{pizza.name}}
      </div>
      <div class="col-md offset-md-2 mt-4">
        {{pizza.price}} <!-- 显示实际价格 -->
      </div>
      <div class="col-sm-2 mt-4">
        <button class="btn btn-primary" type="submit">Add</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue' // 导入ref创建响应式变量
import { api } from "@/api.js"

// 用ref初始化响应式数组,空数组比null更适合v-for场景
const pizzas = ref([])

const getPizzas = async () => {
  // 去掉冗余的then,直接用await接收响应
  const response = await api.get('pizza/pizzas/')
  pizzas.value = response.data // ref变量要通过.value赋值
}

// 组件创建时自动调用(相当于Vue2的created钩子)
getPizzas()
</script>

关键改动说明

  • 使用ref([])创建响应式数组,确保数据更新后模板能同步渲染
  • 统一用async/await处理异步请求,避免await和.then()混用
  • 给v-for设置唯一的pizza.id作为key,符合Vue性能优化要求
  • 添加加载状态提示,避免API请求期间页面空白

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:30:47