跳至主要内容

为了方便编写,直接在组件内部声明的片段会成为这些组件上的属性。将 headerrow 片段移动到 <FilteredList> 内部

App
<FilteredList
	data={colors}
	field="name"
	{header}
	{row}
>
	{#snippet header()}...{/snippet}

	{#snippet row(d)}...{/snippet}
</FilteredList>

{#snippet header()}...{/snippet}

{#snippet row(d)}...{/snippet}

现在我们可以从显式属性中删除它们了

App
<FilteredList data={colors} field="name" {header} {row}>
	{#snippet header()}...{/snippet}

	{#snippet row(d)}...{/snippet}
</FilteredList>

组件内部不是声明片段一部分的任何内容都将成为一个特殊的 children 片段。由于 header 没有参数,我们可以通过删除块标签将其转换为 children...

App
{#snippet header()}
<header>
	<span class="color"></span>
	<span class="name">name</span>
	<span class="hex">hex</span>
	<span class="rgb">rgb</span>
	<span class="hsl">hsl</span>
</header>
{/snippet}

...并在另一侧将 header 属性重命名为 children

FilteredList
<script>
	let { data, field, children, row } = $props();

	// ...
</script>
FilteredList
<div class="header">
	{@render children()}
</div>

在 GitHub 上编辑此页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<script>
	import FilteredList from './FilteredList.svelte';
	import { colors } from './data.js';
</script>
 
<FilteredList
	data={colors}
	field="name"
	{header}
	{row}
></FilteredList>
 
{#snippet header()}
	<header>
		<span class="color"></span>
		<span class="name">name</span>
		<span class="hex">hex</span>
		<span class="rgb">rgb</span>
		<span class="hsl">hsl</span>
	</header>
{/snippet}
 
{#snippet row(d)}
	<div class="row">
		<span class="color" style="background-color: {d.hex}"></span>
		<span class="name">{d.name}</span>
		<span class="hex">{d.hex}</span>
		<span class="rgb">{d.rgb}</span>
		<span class="hsl">{d.hsl}</span>
	</div>
{/snippet}
 
<style>
	header, .row {
		display: grid;
		align-items: center;
		grid-template-columns: 2em 4fr 3fr;
		gap: 1em;
		padding: 0.1em;
		background: var(--bg-1);
		border-radius: 0.2em;
	}
 
	header {
		font-weight: bold;
	}
 
	.row:hover {
		background: var(--bg-2);
	}
 
	.color {
		aspect-ratio: 1;
		height: 100%;
		border-radius: 0.1em;
	}
 
	.rgb, .hsl {
		display: none;
	}
 
	@media (min-width: 40rem) {
		header, .row {
			grid-template-columns: 2em 4fr 3fr 3fr;
		}
 
		.rgb {
			display: block;
		}
	}
 
	@media (min-width: 60rem) {
		header, .row {
			grid-template-columns: 2em 4fr 3fr 3fr 3fr;
		}
 
		.hsl {
			display: block;
		}
	}
</style>