是否可以在运行时动态加载 Svelte 模板?
Is it possible to dynamically load a Svelte template at runtime?
我查看了 [<svelte:component>]
(here) 的文档,但看起来我必须在编译时 import
所有可能的模板。
在 Svelte 中是否可以根据用户操作从类似 fetch()
的调用中加载任意数量的任意模板?然后往里面注入数据?
如果我计划在初始加载后更新它,使用 <slot>
会不会效率低下?
从技术上讲,从源文本创建组件是可能的——例如,the REPL does it——因为编译器不关心它是 运行 在 Node 还是浏览器中。但是绝对不推荐! (这会破坏使用 Svelte 的目的,因为编译器有点大。)
相反,如果您使用 Rollup(使用 experimentalDynamicImport
和 experimentalCodeSplitting
)或 webpack,您可以动态导入组件本身:
<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:component>]
(here) 的文档,但看起来我必须在编译时 import
所有可能的模板。
在 Svelte 中是否可以根据用户操作从类似 fetch()
的调用中加载任意数量的任意模板?然后往里面注入数据?
如果我计划在初始加载后更新它,使用 <slot>
会不会效率低下?
从技术上讲,从源文本创建组件是可能的——例如,the REPL does it——因为编译器不关心它是 运行 在 Node 还是浏览器中。但是绝对不推荐! (这会破坏使用 Svelte 的目的,因为编译器有点大。)
相反,如果您使用 Rollup(使用 experimentalDynamicImport
和 experimentalCodeSplitting
)或 webpack,您可以动态导入组件本身:
<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>