Vue3 <script setup>使用顶层await后模板无法渲染问题求助
问题原因
- Vue3中
<script setup>使用顶层await时,组件会被自动标记为异步组件,必须配合内置的<Suspense>组件包裹才能正常渲染。如果没有外层<Suspense>处理异步挂起状态,组件会一直处于待加载状态,最终表现为页面空白。
解决方案
方案1:外层添加<Suspense>组件(官方推荐)
在引用该异步组件的父组件中,用<Suspense>包裹组件,同时可以自定义加载 fallback 状态:
<template> <Suspense> <template #default> <!-- 你的异步库存组件 --> <Inventory /> </template> <template #fallback> <div>数据加载中,请稍候...</div> </template> </Suspense> </template> <script setup lang="ts"> import Inventory from './Inventory.vue' </script>
方案2:放弃顶层await,改用生命周期钩子发起请求
如果不想引入<Suspense>,可以调整组件内部逻辑,把异步请求放到onMounted钩子中执行,用ref存储响应式数据即可:
<script setup lang="ts"> import { ref, onMounted } from 'vue' import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory' // 初始化空数组作为默认值 const inventory = ref<GetInventoryResponse>([]) onMounted(async () => { inventory.value = await apiGetInventory() }) </script>
额外注意
你当前模板的表格表头写法存在问题,<tr>是行标签,<th>是表头单元格标签,正确写法如下,避免后续表格渲染异常:
<thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead>
内容的提问来源于stack exchange,提问作者olvenmage
相关产品推荐
相关产品推荐

