【问题标题】:Svelte : Importing component dynamically is not workingSvelte:动态导入组件不起作用
【发布时间】:2020-12-20 07:03:55
【问题描述】:

我想动态插入组件。但是,它失败了。有人能告诉我这件事和解决这个问题的建议吗? REPL 在这里。

<script>
let Chatbox;
function loadChatbox() {
    // this is available.
    // import('./ChatBox.svelte').then(res => Chatbox = res.default)
    // but, this is not. Why?? and How to make it??
    const name = './ChatBox.svelte';
    import(name).then(res => Chatbox = res.default)
}
</script>
<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />

【问题讨论】:

    标签: javascript svelte


    【解决方案1】:

    您为什么要尝试分离组件路径?我相信如果你只是把你的代码改成这个就行了。

    import('./ChatBox.svelte').then(res => Chatbox = res.default)
    

    Dynamically loading component using import or fetch

    【讨论】:

    • 感谢您的回复。我编辑了我的代码。我需要使用一个变量来动态导入。
    【解决方案2】:

    尝试添加“等待”:

    <script>
    let Chatbox;
    async function loadChatbox() { // need to make this an async function too
        // this is available.
        // import('./ChatBox.svelte').then(res => Chatbox = res.default)
        // but, this is not. Why?? and How to make it??
        const name = './ChatBox.svelte';
        (await import(name)).then(res => Chatbox = res.default) // added await
    }
    </script>
    <button on:click="{loadChatbox}">Load chatbox</button>
    <svelte:component this="{Chatbox}" />
    

    【讨论】:

      【解决方案3】:

      我找到了解决方案:https://stackoverflow.com/a/36530495/14858601

      // index.js
      export { default as Template1 } from './Template1';
      export { default as Template2 } from './Template2';
      
      
      // OtherComponent.js
      import * as templates from './index.js'
      ...
      // handy to be able to fall back to a default!
      return templates[name] || templates.Template1;
      

      【讨论】:

        猜你喜欢
        • 2021-06-01
        • 2021-11-16
        • 2023-02-02
        • 2022-11-07
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 2023-04-02
        相关资源
        最近更新 更多