在 <svelte:component> 中使用字符串作为组件名称

Using string as a component name in <svelte:component>

假设我们在 Svelte 中有一个使用动态特殊标签创建的自定义组件。假设我们有一个带有组件构造函数名称的 string

<script>
    import testComponent from './Something.svelte';

    let componentConstructorName = 'testComponent';
</script>

<svelte:component this="{componentConstructorName}" />

是否可以在this属性中直接解析组件构造函数名并渲染对应的组件?

我知道我可以创建一个对象,将构造函数引用分配给它的字符串名称,但我正在尝试以更自动化的方式执行此操作,而无需进行任何手动分配。

以下方法可行,但使用 eval().

确实感觉有些痛苦
<svelte:component this="{ eval(componentConstructorName) }" />

不,不可能直接这样做,您将不得不以某种方式从字符串转到构造函数引用。但是,您可以使用第二个反应式变量,而不是真正不推荐的 eval

let componentContructorName = 'testComponent';
$: componentConstructorClass = 
       componentConstructorName === 'testComponent'
     ? testComponent
     : someDefaultComponent

或者可能使用 switch 语句

let componentContructorName = 'testComponent';
$: componentConstructorClass = (() => switch(componentConstructorName) {
     case 'testComponent': return TestComponent;
     case 'testComponent2': return TestComponent2;
     default: someDefaultComponent;
})();

这是我的解决方案,我认为这很 Vuey。

<script>
  import CompOne from './CompOne.svelte';
  import CompTwo from './CompTwo.svelte';
  import CompThree from './CompThree.svelte';


  const components = { CompOne, CompTwo, CompThree }
  let compConstrName = "CompOne";
</script>

<svelte:component this={components[compConstrName]} />