美文网首页
Getting started with Svelte - Lo

Getting started with Svelte - Lo

作者: 游文影月志 | 来源:发表于2023-11-25 17:43 被阅读0次

If blocks

HTML doesn't have a way of expressing logic, like conditionals and loops. Svelte does.

To conditionally render some markup, we wrap it in an if block.

Just like in JavaScript, an if block can have an else block.

Multiple conditions can be 'chained' together with else if.

Note: A # character always indicates a block opening tag. A / character always indicates a block closing tag. A : character, as in {:else}, indicates a block continuation tag.

<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>
{:else if count < 5}
    <p>{count} is less than 5</p>
{:else}
    <p>{count} is between 5 and 10</p>
{/if}

Each blocks

If you need to loop over lists of data, use an each block. The can be any array or array-like object (i.e. it has a length property).

You can get the current index as a second argument.

<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>

Keyed each blocks

By default, when you modify the value of an each block, it will add and remove items at the end of the block, and update any values that have changed. That might not be what you want.

Instead, we'd like to remove only the first <Thing> component and its DOM node, and leave the others unaffected.

To do that, we specify a unique identifier (or "key") for the each block:

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

    let things = [
        { id: 1, name: 'apple' },
        { id: 2, name: 'banana' },
        { id: 3, name: 'carrot' },
        { id: 4, name: 'doughnut' },
        { id: 5, name: 'egg' }
    ];

    function handleClick() {
        things = things.slice(1);
    }
</script>

<button on:click={handleClick}>
    Remove first thing
</button>

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

Note that using a string or number is generally safer, since it means identity persists without referential equality, for example when updating with fresh data from an API server. Remember, do not use the index value i as the key.

Await blocks

Most web applications have to deal with asynchronous(异步) data at some point. Svelte makes it easy to await the value of promises directly in your markup.

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

Only the most recent promise is considered, meaning you don't need to worry about race conditions.

If you know that your promise can't reject, you can omit the catch block. You can also omit the first block if you don't want to show anything until the promise resolves:

{#await promise then number}
    <p>The number is {number}</p>
{/await}
``

相关文章

网友评论

      本文标题:Getting started with Svelte - Lo

      本文链接:https://www.haomeiwen.com/subject/zodgwdtx.html