【问题标题】:Dynamic component import in svelteJSsvelteJS 中的动态组件导入
【发布时间】:2021-07-23 21:18:31
【问题描述】:

我正在使用带有 svelte-spa-router 的 SvelteJs。

我有自己的案例

<script>
import Component1 from './Component1.svelte'
import Component2 from './Component2.svelte'
</script>

    {#if condition}
       <Component1 {...props1} />
    {:else}
       <Component2  {...props2} />
    {/if}

有没有更好的方法可以做到这一点?我可以在满足条件时动态导入和渲染组件吗?

【问题讨论】:

    标签: svelte-3 dynamic-import svelte-component


    【解决方案1】:

    我认为您需要做的称为“延迟加载”,即仅在需要渲染组件时才加载组件。

    这个概念可以用在svelte中,你只需要&lt;svelte:component /&gt;import('')函数

    // Component.svelte
    <div>
        Hello world
    </div>
    

    让我们动态导入该组件

    <script>
        export let props = {}
        export let condition = false
    </script>
    
    {#await import('./Component.svelte') then value }
        <svelte:component this={value.default} {...props} />
    {/await}
    

    让我们添加一个条件

    {#if condition}
      {#await import('./Component.svelte') then value }
            <svelte:component this={value.default} {...props} />
        {/await}
    {/if}
    

    现在组件只有在满足条件时才会被导入

    你检查这个REPL

    【讨论】:

    • 正是我即将发布的解决方案。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2020-06-18
    • 2019-02-03
    • 2018-11-21
    • 2018-06-24
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多