按名称动态调用 class(字符串到 class 名称)
Call class dynamically by name (string to class name)
我正在用 Svelte 制作一个非常简单的路由器。通过传递 currentHash 将页面作为组件导入(例如:/#Dashboard
):
import Dashboard from './Dashboard.svelte';
import About from './About.svelte';
import NotFound from './404.svelte';
let component = currentHash; // 'Dashboard' as string
稍后,我使用以下方法加载组件:
<svelte:component this={component} />
这不起作用,因为此函数不接受字符串,而是 class 本身。
唯一有效的是 let component = eval(currentHash);
,它有效但我不想使用 eval
。
也,累component = window[currentHash]
;这也不管用。
如何将字符串变量转换为 Class 调用?
您将需要了解所有可能呈现的组件并自行实现映射
<script>
import Dashboard from './Dashboard.svelte';
import About from './About.svelte';
import NotFound from './404.svelte';
const componentMap = {
Dashboard,
About,
NotFound
}
let component = currentHash;
</script>
<svelte:component this={componentMap[currentHash]} />
我正在用 Svelte 制作一个非常简单的路由器。通过传递 currentHash 将页面作为组件导入(例如:/#Dashboard
):
import Dashboard from './Dashboard.svelte';
import About from './About.svelte';
import NotFound from './404.svelte';
let component = currentHash; // 'Dashboard' as string
稍后,我使用以下方法加载组件:
<svelte:component this={component} />
这不起作用,因为此函数不接受字符串,而是 class 本身。
唯一有效的是 let component = eval(currentHash);
,它有效但我不想使用 eval
。
也,累component = window[currentHash]
;这也不管用。
如何将字符串变量转换为 Class 调用?
您将需要了解所有可能呈现的组件并自行实现映射
<script>
import Dashboard from './Dashboard.svelte';
import About from './About.svelte';
import NotFound from './404.svelte';
const componentMap = {
Dashboard,
About,
NotFound
}
let component = currentHash;
</script>
<svelte:component this={componentMap[currentHash]} />