Javascript 苗条:动态导入组件不起作用
我想动态插入组件。但是,它失败了。你能告诉我这件事和解决这个问题的建议吗? 在这里Javascript 苗条:动态导入组件不起作用,javascript,svelte,Javascript,Svelte,我想动态插入组件。但是,它失败了。你能告诉我这件事和解决这个问题的建议吗? 在这里 让聊天室; 函数loadChatbox(){ //这是可用的。 //导入('./ChatBox.svelte')。然后(res=>ChatBox=res.default) //但是,这不是。为什么?怎么做?? const name='./ChatBox.svelte'; 导入(名称)。然后(res=>Chatbox=res.default) } 加载聊天室 为什么要尝试分离组件路径?我相信如果你把你的代码改成这
让聊天室;
函数loadChatbox(){
//这是可用的。
//导入('./ChatBox.svelte')。然后(res=>ChatBox=res.default)
//但是,这不是。为什么?怎么做??
const name='./ChatBox.svelte';
导入(名称)。然后(res=>Chatbox=res.default)
}
加载聊天室
为什么要尝试分离组件路径?我相信如果你把你的代码改成这个,它会工作的
import('./ChatBox.svelte').then(res => Chatbox = res.default)
请参见尝试添加“等待”:
让聊天室;
异步函数loadChatbox(){//也需要将其设置为异步函数
//这是可用的。
//导入('./ChatBox.svelte')。然后(res=>ChatBox=res.default)
//但是,这不是。为什么?怎么做??
const name='./ChatBox.svelte';
(wait import(name))。然后(res=>Chatbox=res.default)//添加了wait
}
加载聊天室
我找到了解决方案:
谢谢你的回复。我编辑了我的代码。我需要使用一个变量来动态导入。我尝试了这个方法,但不起作用--;
import('./ChatBox.svelte').then(res => Chatbox = res.default)
<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}" />
// 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;