问题
I have looked at the documentation for [<svelte:component>]
(here), but that looks like I would have had to import
all of the possible templates at compile time.
Is it possible in Svelte to load any number of arbitrary templates from something like a fetch()
call based on a user action? Then inject data into it?
Would it be inefficient to use <slot>
for something like this, if I plan on updating it after the initial load?
回答1:
It's technically possible to create a component from the source text — the REPL does it, for example — since the compiler doesn't care if it's running in Node or the browser. But it's definitely not recommended! (It would defeat the object of using Svelte, since the compiler is somewhat large.)
Instead, you can dynamically import the components themselves, if you're using Rollup (with experimentalDynamicImport
and experimentalCodeSplitting
) or 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>
来源:https://stackoverflow.com/questions/50300176/is-it-possible-to-dynamically-load-a-svelte-template-at-runtime