Condicionales y operadores lógicos en Svelte

Image for post
Image for post

{#if …}

<script>
let user = { loggedIn: false };
function toggle() {
user.loggedIn = !user.loggedIn;
}
</script>
{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{/if}
{#if !user.loggedIn}
<button on:click={toggle}>
Log in
</button>
{/if}

{:else …}

<script>
let user = { loggedIn: false };
function toggle() {
user.loggedIn = !user.loggedIn;
}
</script>
{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{:else}
<button on:click={toggle}>
Log in
</button>
{/if}

{:else if …}

<script>
let x = 7;
</script>
{#if x > 10}
<p>{x} es mayor que 10</p>
{:else if 5 > x}
<p>{x} es menor que 5</p>
{:else}
<p>{x} está entre 5 y 10</p>
{/if}
7 está entre 5 y 10

{:each}

<script>
let perros = [
{ id: 123, name: 'Max' },
{ id: 456, name: 'Leo' },
{ id: 789, name: 'Nina' }
];
</script>
<ul>
{#each perros as perro}
<li>
{perro.name}
</li>
{/each}
</ul>
<ul>
<li>Max</li>
<li>Leo</li>
<li>Nina</li>
</ul>
<script>
let perros = [
{ id: 123, name: 'Max' },
{ id: 456, name: 'Leo' },
{ id: 789, name: 'Nina' }
];
</script>
<ul>
{#each perros as perro, indice}
<li>
{indice + 1}: {perro.name}
</li>
{/each}
</ul>
<ul>
<li>1. Max</li>
<li>2. Leo</li>
<li>3. Nina</li>
</ul>

{#await}

{#await promise}
<p>...esperando</p>
{:then number}
<p>El número es {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store