如何在Svelte/Sapper中动态导入和渲染组件?
How to import and render components dynamically in Svelte/Sapper?
我有一个组件 (IconInline.html
),我想在其中根据传递给它的道具 (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>
有没有办法
- 动态导入给定目录中的所有组件?
- 渲染与给定道具匹配的特定组件?
无法导入给定目录中的所有组件,但您可以使用 <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>
我有一个组件 (IconInline.html
),我想在其中根据传递给它的道具 (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>
有没有办法
- 动态导入给定目录中的所有组件?
- 渲染与给定道具匹配的特定组件?
无法导入给定目录中的所有组件,但您可以使用 <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>