面试题答案
一键面试- 在Svelte中创建动态组件的基本步骤:
- 导入需要的组件。例如,假设有
Component1.svelte
和Component2.svelte
两个组件,在主组件中导入它们:
import Component1 from './Component1.svelte'; import Component2 from './Component2.svelte';
- 定义一个变量来决定渲染哪个组件。比如:
let selectedComponent = Component1;
- 使用
<svelte:component>
标签来动态渲染组件。将定义的变量作为this
属性的值传递给<svelte:component>
:
<svelte:component this={selectedComponent} />
- 导入需要的组件。例如,假设有
- 向动态组件传递不同类型的参数:
- 字符串参数:在
<svelte:component>
标签上像普通HTML属性一样添加属性名和值。例如,如果动态组件有一个接受字符串的title
属性:
<svelte:component this={selectedComponent} title="This is a string" />
- 数字参数:同样在
<svelte:component>
标签上添加属性,Svelte会自动解析数字。比如组件有一个接受数字的count
属性:
<svelte:component this={selectedComponent} count={5} />
- 对象参数:定义一个对象变量,然后传递给组件。例如,有一个接受对象的
config
属性:
let myObject = { key: 'value', num: 123 }; <svelte:component this={selectedComponent} config={myObject} />
- 字符串参数:在
- 代码示例:
- Component1.svelte:
<script> export let title; export let count; export let config; </script> <div> <h1>{title}</h1> <p>Count: {count}</p> <p>Config key: {config.key}</p> </div>
- 主组件(假设为App.svelte):
<script> import Component1 from './Component1.svelte'; let selectedComponent = Component1; let myTitle = "Dynamic Component Example"; let myCount = 10; let myObject = { key: 'object value', num: 456 }; </script> <svelte:component this={selectedComponent} title={myTitle} count={myCount} config={myObject} />