Sapper/Svelte 可以有条件地导入组件吗? [英] Sapper/Svelte possible to conditionally import components?

查看:44
本文介绍了Sapper/Svelte 可以有条件地导入组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Sapper 中,我仅在客户端呈现时才尝试导入组件(使用 onMount).有没有类似于 React SuspenseReact.lazy 的东西?或者还有其他方法吗?

In Sapper I am trying to import a component only if being rendered client side (using onMount). Is there something similar to React Suspense and React.lazy? Or is there another approach?

推荐答案

你当然可以那样做,是的:

You can certainly do it that way, yes:

<script>
  import { onMount } from 'svelte';
    
  let Thing;
    
  onMount(async () => {
    Thing = (await import('./Thing.svelte')).default;
  });
</script>

<svelte:component this={Thing} answer={42}>
  <p>some slotted content</p>
</svelte:component>

此处演示.

或者,您可以将其包装到一个组件中:

Alternatively, you could wrap that into a component:

<!-- Loader.svelte -->
<script>
  import { onMount } from 'svelte';
    
  let loader;
  let Component;
    
  onMount(async () => {
    Component = (await loader()).default;
  });
    
  export { loader as this };
</script>

<svelte:component this={Component} {...$$restProps}>
  <slot></slot>
</svelte:component>

{#if !Component}
  <slot name="fallback"></slot>
{/if}

<Loader
  this={() => import('./Thing.svelte')}
  answer={42}
>
  <p>some slotted content</p>
  <p slot="fallback">loading...</p>
</Loader>

此处演示.这种方法的一个警告是 default 以外的插槽不会被转发"到底层组件.

Demo here. A caveat with this approach is that slots other than default won't be 'forwarded' to the underlying component.

这篇关于Sapper/Svelte 可以有条件地导入组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆