跳至主要內容

HTML 沒有表達邏輯的方式,例如條件和迴圈。Svelte 有。

若要有條件地渲染一些標記,我們將其包在 if 區塊中。讓我們新增一些文字,當 count 大於 10 時顯示

App
<button onclick={increment}>
	Clicked {count}
	{count === 1 ? 'time' : 'times'}
</button>

{#if count > 10}
	<p>{count} is greater than 10</p>
{/if}

試試看 — 更新元件,然後點擊按鈕幾次。

在 GitHub 上編輯此頁面

上一個 下一個
1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
	let count = $state(0);
 
	function increment() {
		count += 1;
	}
</script>
 
<button onclick={increment}>
	Clicked {count}
	{count === 1 ? 'time' : 'times'}
</button>