MST

星途 面试题库

面试题:Svelte中如何创建动态组件并传递参数

请描述在Svelte中创建动态组件的基本步骤,并且说明如何向动态组件传递不同类型的参数,例如字符串、数字、对象等。同时,给出一个简单的代码示例。
44.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 在Svelte中创建动态组件的基本步骤
    • 导入需要的组件。例如,假设有Component1.svelteComponent2.svelte两个组件,在主组件中导入它们:
    import Component1 from './Component1.svelte';
    import Component2 from './Component2.svelte';
    
    • 定义一个变量来决定渲染哪个组件。比如:
    let selectedComponent = Component1;
    
    • 使用<svelte:component>标签来动态渲染组件。将定义的变量作为this属性的值传递给<svelte:component>
    <svelte:component this={selectedComponent} />
    
  2. 向动态组件传递不同类型的参数
    • 字符串参数:在<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} />
    
  3. 代码示例
    • 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} />