使用 import 或 fetch 动态加载组件 [英] Dynamically loading component using import or fetch
问题描述
有没有办法使用 fetch 或 import 动态导入 svelte 中的组件?可能是从可共享组件创建的 svelte 文件或模块文件(仍然不知道它是如何工作的).很新,很苗条,很兴奋.
Is there a way to import components in svelte dynamically using fetch or import? May be a svelte file or module file created from shareable component (still don't know how that works). very new with svelte and very excited.
我在 stackoverflow 中找到了一些适用于 v2 的代码.这是链接>
I found some code in stackoverflow, which worked for v2. Here is the link
<button on:click="loadChatbox()">
chat to a customer service representative
</button>
{#if ChatBox}
<svelte:component this={ChatBox}/>
{/if}
<script>
export default {
methods: {
async loadChatbox() {
const { default: Chatbox } = await import('./Chatbox.html');
this.set({ Chatbox });
}
}
};
</script>
推荐答案
Svelte 3 中存在相同的功能,但您只需要将动态导入的组件分配给用于 this
svelte:component
上的 code> 属性.
The same functionality exists in Svelte 3, but you only need to assign the dynamically imported component to a regular variable that you use for the this
property on the svelte:component
.
示例(REPL)
<!-- App.svelte -->
<script>
let Chatbox;
function loadChatbox() {
import('./ChatBox.svelte').then(res => Chatbox = res.default)
}
</script>
<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />
<!-- ChatBox.svelte -->
<h1>Dynamically loaded chatbox</h1>
<input />
这篇关于使用 import 或 fetch 动态加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!