阅读(3053) (0)

Svelte Slots

2023-02-22 15:07:57 更新

就像元素可以有子元素一样......

<div>
	<p>I'm a child of the div</p>
</div>

...组件也可以。然而,在一个组件可以接受子元素之前,它需要知道把他们放在哪里。我们使用 ​<slot>​ 元素来做到这一点。将其放入 ​Box.svelte​ 中:

<div class="box">
	<slot></slot>
</div>

你现在可以把东西放在盒子里了:

<Box>
	<h2>Hello!</h2>
	<p>This is a box. It can contain anything.</p>
</Box>

示例代码

  • App.svelte

<script>
	import Box from './Box.svelte';
</script>

<Box>
	<h2>Hello!</h2>
	<p>This is a box. It can contain anything.</p>
</Box>

  • Box.svelte

<style>
	.box {
		width: 300px;
		border: 1px solid #aaa;
		border-radius: 2px;
		box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
		padding: 1em;
		margin: 0 0 1em 0;
	}
</style>

<div class="box">
	<slot></slot>
</div>