Bạn có thể sử dụng logic trong Svelte như sau:

If

<script>
	let count = 0;

	function increment() {
		count += 1;
	}
</script>

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

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

Else

{#if count > 10}
	<p>{count} is greater than 10</p>
{:else if count < 5}
	<p>{count} is less than 5</p>
{:else}
	<p>{count} is between 5 and 10</p>
{/if}
Svelte

Each

<script>
	const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
	let selected = colors[0];
</script>

<h1 style="color: {selected}">Pick a colour</h1>

<div>
	{#each colors as color, i}
		<button
			aria-current={selected === color}
			aria-label={color}
			style="background: {color}"
			on:click={() => selected = color}
		>{i + 1}</button>
	{/each}
</div>

<style>
	h1 {
		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;
	}

	button[aria-current="true"] {
		transform: none;
		filter: none;
		box-shadow: inset 3px 3px 4px rgba(0,0,0,0.2);
	}
</style>
Svelte

Trong Each chúng ta có thể sử dụng như sau:

{#each things as thing (thing.id)}
	<Thing name={thing.name} />
{/each}
Svelte

(thing.id) là cách xác định một unique identifier cho mỗi phần tử trong mảng khi nó được lặp qua. Điều này giúp Svelte hiểu cách xác định và theo dõi sự thay đổi của từng phần tử riêng lẻ để render lại chỉ phần tử đó khi có sự thay đổi, thay vì render lại toàn bộ danh sách.

Khi có sự thay đổi trong things, Svelte sẽ sử dụng thing.id để xác định xem phần tử nào đã thay đổi và chỉ render lại phần tử đó trong DOM thay vì render lại tất cả các phần tử. Điều này giúp cải thiện hiệu suất render trong trường hợp có nhiều phần tử trong danh sách.

Await

util.js

export async function getRandomNumber() {
    // Fetch a random number between 0 and 100
    // (with a delay, so that we can see it)
    const res = await fetch('/random-number');

    if (res.ok) {
        return await res.text();
    } else {
        // Sometimes the API will fail!
        throw new Error('Request failed');
    }
}
JavaScript

App.svelte

<script>
	import { getRandomNumber } from './utils.js';

	let promise = getRandomNumber();

	function handleClick() {
		promise = getRandomNumber();
	}
</script>

<button on:click={handleClick}>
	generate random number
</button>

{#await promise}
	<p>...waiting</p>
{:then number}
	<p>The number is {number}</p>
{:catch error}
	<p style="color: red">{error.message}</p>
{/await}
Svelte

Leave a Reply

Your email address will not be published. Required fields are marked *