(vue3) Asynchronous components & code subcontracting & suspense

asynchronous component

In large applications, we may need to split the application into smaller code blocks and reduce the size of the main package

At this time, you can use asynchronous components

top floor await

在setup语法糖里面 使用方法

<script setup> The top layer can be used in  await. The resulting code will be compiled into async setup()

<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>

The parent component references the child component through defineAsyncComponent to load asynchronously and cooperate with the import function mode to subcontract

<script setup lang="ts">
import { reactive, ref, markRaw, toRaw, defineAsyncComponent } from 'vue'
 
const Dialog = defineAsyncComponent(() => import('../../components/Dialog/index.vue'))
 
//完整写法
 
const AsyncComp = defineAsyncComponent({
  // 加载函数
  loader: () => import('./Foo.vue'),
 
  // 加载异步组件时使用的组件
  loadingComponent: LoadingComponent,
  // 展示加载组件前的延迟时间,默认为 200ms
  delay: 200,
 
  // 加载失败后展示的组件
  errorComponent: ErrorComponent,
  // 如果提供了一个 timeout 时间限制,并超时了
  // 也会显示这里配置的报错组件,默认值是:Infinity
  timeout: 3000
})

suspense

<suspense> The component has two slots. They both receive only one direct child node. default Nodes in slots are displayed as much as possible. If not, show  fallback the node in the slot.

     <Suspense>
            <template #default>
                <Dialog>
                    <template #default>
                        <div>我在哪儿</div>
                    </template>
                </Dialog>
            </template>
 
            <template #fallback>
                <div>loading...</div>
            </template>
        </Suspense>

Je suppose que tu aimes

Origine blog.csdn.net/weixin_45959965/article/details/130045533
conseillé
Classement