MST
星途 面试题库

面试题:Svelte中懒加载组件的基本实现方式

在Svelte中,如何实现组件的懒加载?请简述基本步骤,并给出一个简单示例代码。
30.4万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

基本步骤

  1. 创建懒加载组件:正常编写需要懒加载的Svelte组件。
  2. 使用 {#await}import():在父组件中,通过 import() 动态导入懒加载组件,import() 返回一个Promise。使用 {#await} 块来处理这个Promise,在加载过程中可以显示加载状态(如加载动画),加载完成后渲染组件。

示例代码

  1. 懒加载组件 LazyComponent.svelte
<script>
    let message = 'This is a lazy - loaded component';
</script>

<div>
    <p>{message}</p>
</div>
  1. 父组件 App.svelte
<script>
    let promise;
    $: promise = import('./LazyComponent.svelte');
</script>

{#await promise}
    <p>Loading...</p>
{:then LazyComponent}
    <LazyComponent />
{:catch error}
    <p>Error: {error.message}</p>
{/await}