如何在Svelte / Sapper中动态导入和渲染组件?

时间:2018-04-30 14:30:05

标签: svelte

我有一个组件(IconInline.html),我希望在其中根据传递给它的prop(IconID}动态导入和呈现组件。

目前我手动这样做:



{{#if IconID === "A"}}
    <A />
{{elseif IconID === "B"}}
    <B />
{{elseif IconID === "C"}}
    <C />
{{elseif IconID === "D"}}
    <D />
{{/if}}

<script>
    import A from "./icons/A.html";
    import B from "./icons/B.html";
    import C from "./icons/C.html";
    import D from "./icons/D.html";

    export default {
        components: { A, B, C, D }
    };
</script>
&#13;
&#13;
&#13;

有没有办法

  1. 动态导入给定目录中的所有组件?
  2. 渲染与给定道具匹配的特定组件?

1 个答案:

答案 0 :(得分:1)

无法导入给定目录中的所有组件,但您可以使用<svelte:component>呈现与特定道具匹配的组件:

<svelte:component this={cmp} foo="bar" baz="bop">
  <!-- contents go here -->
</svelte:component>

<script>
  import A from "./icons/A.html";
  import B from "./icons/B.html";
  import C from "./icons/C.html";
  import D from "./icons/D.html";

  const components = { A, B, C, D };

  export default {
    computed: {
      cmp: ({ IconID }) => components[IconID]
    }
  };
</script>

如果IconID"A",则相当于

<A foo="bar" baz="bop">
  <!-- contents go here -->
</A>

Docs here.