• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

是否可以在运行时动态加载 Svelte 模板?

用户头像
it1352
帮助1

问题说明

我查看了 [] 的文档(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?

正确答案

#1

技术上可以从源文本创建组件 — 例如,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>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhgge
系列文章
更多 icon
同类精品
更多 icon
继续加载