我在 Vue 3 中使用新语法,我真的很喜欢它的想法,但是一旦我尝试使用顶级等待,我就开始遇到一些问题。
这是我的代码:
<template>
<div class="inventory">
<a class="btn btn-primary">Test button</a>
<table class="table">
<thead>
<tr>Name</tr>
<tr>Description</tr>
</thead>
<tbody>
<tr v-for="(item, key) in inventory" :key="key">
<td>{{ item.name }}</td>
<td>{{ item.description }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup lang="ts">
import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory'
const inventory: GetInventoryResponse = await apiGetInventory()
</script>
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,它并没有那么复杂, apiGetInventory 只是一个 axios 调用,所以我不会费心去讨论它。问题是,如果我有这个顶级等待,我的模板将不再呈现,它只是浏览器中的一个空白页面。如果我删除这两行代码,它就可以正常工作。而且这个承诺似乎运行得很好,如果我在它下面放置一个 console.log(inventory) ,我会得到一个包含所有精美对象的数组。
有人知道这里出了什么问题吗?
问题
我在 Vue.js 3 中使用 async setup(),但我的 HTML 内容消失了。我的组件模板没有插入到 HTML,但是当我删除 async 和 await 前缀时,我的 HTML 内容又回来了。我怎样才能解决这个问题?
async setup () {
const data = ref(null)
try {
const res = await fetch('api')
data.value = res.json()
}
catch (e) {
console.error(e)
}
return {
data
}
}
Run Code Online (Sandbox Code Playgroud)
我试过了
<Suspense>标签,但仍然是同样的问题<script lang="ts">
import { createComponent } from "@vue/composition-api";
import { SplashPage } from "../../lib/vue-viewmodels";
export default createComponent({
async setup(props, context) {
await SplashPage.init(2000, context.root.$router, "plan", "login");
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
错误:“设置”必须返回“对象”或“函数”,得到“承诺”