Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
小主,接下来这一招不但威力大,用好了还能帮你节省大量元气。
在开发时我们经常需要跟列表数据打交道。比如在这个练习里我们需要重复使用<button>标签好几次,每次就是改下颜色,还不知道啥时侯添加完。
与其这样费体力的复制粘贴不如使用each代码块:
When building user interfaces you’ll often find yourself working with lists of data. In this exercise, we’ve repeated the
<button>markup multiple times — changing the colour each time — but there’s still more to add. Instead of laboriously copying, pasting and editing, we can get rid of all but the first button, then use aneachblock:
<div>
	{#each colors as color}
		<button
			style="background: red"
			aria-label="red"
			aria-current={selected === 'red'}
			onclick={() => selected = 'red'}
		></button>
	{/each}
</div>注意这里的表达式 (
colors) 可以是任何可迭代的对象,也就是像数组的对象, 换句话说只要能用在Array.from的都可以。
The expression (
colors, in this case) can be any iterable or array-like object — in other words, anything that works withArray.from现在我们可以把"red"换成color变量 Now we need to use thecolorvariable in place of"red":
<div>
	{#each colors as color}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		></button>
	{/each}
</div>你还可以使用第二个参数获取当前元素在列表中的 索引
You can get the current index as a second argument, like so:
<div>
	{#each colors as color, i}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		>{i + 1}</button>
	{/each}
</div><script>
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
let selected = $state(colors[0]);
</script>
<h1 style="color: {selected}">Pick a colour</h1><div>
<button
style="background: red"
aria-label="red"
		aria-current={selected === 'red'}		onclick={() => selected = 'red'}></button>
<button
style="background: orange"
aria-label="orange"
		aria-current={selected === 'orange'}		onclick={() => selected = 'orange'}></button>
<button
style="background: yellow"
aria-label="yellow"
		aria-current={selected === 'yellow'}		onclick={() => selected = 'yellow'}></button>
<!-- TODO add the rest of the colours -->
<button></button>
<button></button>
<button></button>
<button></button>
</div>
<style>
	h1 {font-size: 2rem;
font-weight: 700;
transition: color 0.2s;
}
	div {display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 5px;
max-width: 400px;
}
	button {aspect-ratio: 1;
border-radius: 50%;
background: var(--color, #fff);
transform: translate(-2px,-2px);
filter: drop-shadow(2px 2px 3px rgba(0,0,0,0.2));
transition: all 0.1s;
color: black;
font-weight: 700;
font-size: 2rem;
}
	button[aria-current="true"] {transform: none;
filter: none;
box-shadow: inset 3px 3px 4px rgba(0,0,0,0.2);
}
</style>