add some logic chapters

pull/2143/head
Richard Harris 7 years ago
parent 487b14cb84
commit 5eb2da0898

@ -0,0 +1,15 @@
<script>
let user = { loggedIn: false };
function toggle() {
user.loggedIn = !user.loggedIn;
}
</script>
<button on:click={toggle}>
Log out
</button>
<button on:click={toggle}>
Log in
</button>

@ -0,0 +1,19 @@
<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}

@ -0,0 +1,23 @@
---
title: 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:
```html
{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{/if}
{#if !user.loggedIn}
<button on:click={toggle}>
Log in
</button>
{/if}
```
Try it — update the component, and click on the buttons.

@ -0,0 +1,19 @@
<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}

@ -0,0 +1,17 @@
<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}

@ -0,0 +1,19 @@
---
title: Else blocks
---
Since the two conditions — `if user.loggedIn` and `if !user.loggedIn` — are mutually exclusive, we can simplify this component slightly by using an `else` block:
```html
{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{:else}
<button on:click={toggle}>
Log in
</button>
{/if}
```
> 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. Don't worry — you've already learned almost all the syntax Svelte adds to HTML.

@ -37,7 +37,7 @@ Side-quest: create a 'Svelte for new developers' blog post that assumes no knowl
## Logic ## Logic
* [ ] If blocks * [x] If blocks
* [ ] Else/elseif blocks * [ ] Else/elseif blocks
* [ ] Each blocks * [ ] Each blocks
* [ ] Keyed each blocks (maybe? kind of need to cover transitions before we can make this obvious) * [ ] Keyed each blocks (maybe? kind of need to cover transitions before we can make this obvious)

Loading…
Cancel
Save