面试题答案
一键面试具名Slot的应用
具名Slot允许在组件模板的不同位置渲染不同的内容。在Svelte中,组件可以定义多个具名Slot,父组件在使用该组件时,通过name
属性指定内容填充到哪个具名Slot中。
例如,假设我们有一个Card
组件,它有一个标题具名Slot和一个内容具名Slot:
<!-- Card.svelte -->
<div class="card">
<slot name="title"></slot>
<div class="card-content">
<slot name="content"></slot>
</div>
</div>
父组件使用Card
组件并填充具名Slot:
<!-- App.svelte -->
<Card>
<h1 slot="title">My Card Title</h1>
<p slot="content">This is the content of my card.</p>
</Card>
作用域Slot的应用
作用域Slot允许子组件向父组件传递数据,父组件在填充Slot时可以使用这些数据进行个性化渲染。子组件通过let:
语法将数据传递给父组件。
假设我们有一个List
组件,它渲染一个列表项数组,并通过作用域Slot将每个列表项传递给父组件,以便父组件可以根据每个列表项进行个性化渲染:
<!-- List.svelte -->
<ul>
{#each items as item}
<li>
<slot {item}>{item.text}</slot>
</li>
{/each}
</ul>
<script>
export let items = [];
</script>
父组件使用List
组件并通过作用域Slot接收数据进行个性化渲染:
<!-- App.svelte -->
<List {items}>
{#if item.isSpecial}
<strong>{item.text}</strong>
{:else}
{item.text}
{/if}
</List>
<script>
import List from './List.svelte';
const items = [
{ text: 'Normal Item', isSpecial: false },
{ text: 'Special Item', isSpecial: true }
];
</script>
在上述代码中,List
组件通过slot {item}
将当前列表项item
传递给父组件,父组件在填充Slot时可以根据item
的属性进行个性化渲染。