Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active November 3, 2022 20:44
Show Gist options
  • Save crshmk/76f4bda32523ff7f341ffb068b18c361 to your computer and use it in GitHub Desktop.
Save crshmk/76f4bda32523ff7f341ffb068b18c361 to your computer and use it in GitHub Desktop.
Learn Svelte in a gist
<script>
let x
</script>
<p>markup</p>
<style>
body {
background: white;
}
</style>
<script>
let x = 42
</script>
<p>x is {x}</p>
<script>
let x = 1
let onClick = () => x = 2
</script>
<button on:click={onClick}>change 1 to 2</button>
<script>
let x = '';
</script>
<input type="text" bind:value={x}>
<script>
let x = 'green';
</script>
<p style="color: {x}">hi</p>
<button disabled={x !== 'green'}>hi</button>
<script>
let x = 1
let y = 2
let z = x + y
</script>
<p>{z}</p>
<script>
let xs = ['one', 'two']
</script>
<div>
{#each xs as x}
<p>{x}</p>
{/each}
</div>
<script>
let xs = []
</script>
<div>
{#each xs as x}
<p>{x}</p>
{:else}
<p>no xs in state</p>
{/each}
</div>
<script>
let x = 10
</script>
<div>
{#if x > 10}
<p>gt 10</p>
{:else if x < 10}
<p>lt 10</p>
{:else}
<p>eq 10</p>
{/if}
</div>
<script>
import Child from './Child.svelte'
</script>
<div>
<Child />
</div>
<script>
import X from './X.svelte'
</script>
<X>
<p>hi</p>
</X>
//X.svelte
<div>
<p>let's say hi:</p>
<slot></slot>
</div>
<script>
import X from './X.svelte'
</script>
<div>
<X>
<p slot="greet">hi</p>
<p>unnamed slot</p>
</X>
</div>
<!-- X.svelte -->
<div>
<slot name="greet"></slot>
<p>we just said hello</p>
<!-- the unnamed slot -->
<slot></slot>
</div>
// more slot api features https://svelte.dev/docs#slots_object
<script>
let isRed = true
</script>
<p class:red={isRed}>hi</p>
<style>
.red {
background: red;
}
</style>
<!-- Child.svelte -->
<script>
export let x = 'default value'
</script>
<p>{x}</p>
<!-- Parent.svelte -->
<script>
let x = 'displayed value'
</script>
<Child x={x} />
<!-- Parent.svelte can pass as -->
<Child {x} />
<!-- Parent.svelte -->
<script>
let isShowing = false
let showThing = () => isShowing = true
</script>
<div>
<Child on:click={showThing} />
{#if isShowing}
<p>hi</p>
{/if}
</div>
<!-- Child.svelte -->
<button on:click>show thing</button>
<button on:click|preventDefault>hi</button>
<!-- https://svelte.dev/docs#on_element_event -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment