子组件:
my-project\src\components\AsyncShow.vue
<template>
<h1>{{ result }}</h1>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
setup() {
return new Promise((resolve) => {
setTimeout(() => {
return resolve({
result: 42,
});
}, 3000);
});
},
});
</script>
使用:
父组件:
my-project\src\App.vue
<template>
<Suspense>
<!-- 请求成功返回的数据 -->
<template #default>
<async-show />
</template>
<!-- 请求失败显示的数据 -->
<template #fallback>
<h1>Loading !...</h1>
</template>
</Suspense>
</template>
<script lang="ts">
import AsyncShow from "./components/AsyncShow.vue";
export default {
name: "App",
components: {
AsyncShow,
},
</script>
效果:3秒后显示结果

文章展示了如何在Vue中使用TypeScript编写异步组件AsyncShow,该组件通过Promise延迟3秒返回数据。在父组件App.vue中,利用Suspense组件进行加载状态管理,当异步组件数据请求成功时显示组件内容,失败时显示加载提示。
2833

被折叠的 条评论
为什么被折叠?



