是否可以在运行时动态加载 Svelte 模板? [英] Is it possible to dynamically load a Svelte template at runtime?

查看:48
本文介绍了是否可以在运行时动态加载 Svelte 模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了 [] 的文档(here),但看起来我必须在编译时import所有可能的模板.

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.

在 Svelte 中是否可以根据用户操作从诸如 fetch() 调用之类的东西加载任意数量的任意模板?然后往里面注入数据?

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?

推荐答案

技术上可以从源文本创建组件 — 例如,REPL 会这样做——因为编译器并不关心它是在 Node 中运行还是在浏览器中运行.但是绝对不推荐!(这会破坏使用 Svelte 的目的,因为编译器有点大.)

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.)

相反,如果您使用 Rollup(使用 experimentalDynamicImportexperimentalCodeSplitting)或 webpack,您可以动态地导入组件本身:

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>

这篇关于是否可以在运行时动态加载 Svelte 模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆