Skip to content

Instantly share code, notes, and snippets.

@johnpapa
Last active June 29, 2021 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnpapa/97b758467a1a4e7612a3d1df8819a456 to your computer and use it in GitHub Desktop.
Save johnpapa/97b758467a1a4e7612a3d1df8819a456 to your computer and use it in GitHub Desktop.
svelte intro

Svelte Intro Steps

Create Hello World

  1. Open https://svelte.dev/

  2. Run the following commands

    npx degit sveltejs/template hello-world
    
    cd hello-world
    
    npm install
    
    npm run dev

Setup

  1. VS Code
  2. Extensions
  3. Svelte Snippets
    1. Svelte for VS Code
    2. Svelte 3 Snippets

Explore the files

  1. src/main.js is the starting point for the app
  2. Notice we're referring to a component named App in the import statement
  3. The App component targets the HTML body
  4. Opensrc/app.svelte
  5. We have script/template/style
  6. The template is displaying "Hello {name}"
  7. name is defined in the script
  8. change the name

Quick Steps

Hero Detail

  1. Add hero={name: 'John', birth_year: '1999'} object to App.svelte
  2. Create HeroDetail.svelte
  3. export let hero;
  4. Add a label and an input
  5. bind:value={hero.name}
  6. Add HeroDetail to App.svelte
  7. Bind hero={hero}
  8. Bind to the birth_year

Heroes

  1. Create the list of heroes with a snippet
  2. Create HeroesList.svelte
  3. export let heroes;
  4. Add the CSS with a snippet
  5. Show HeroesList in App.svelte (comment out HeroDetail)
  6. Bind to the heroes array
  7. Create <ul>
  8. Create s-each-block
  9. Create <li>

Selection

  1. Create let selectedHero;
  2. on:click={() => selectedHero = hero}
  3. class:selected={selectedHero === hero}

If Block

  1. s-if-block
  2. Show the heroDetail component
  3. Bind the hero to selectedHero

Fetch Data

  1. Stop binding to the HeroesList in App.svelte
  2. Remove the export from let heroes
  3. async function getHeroes() { }
  4. fetch from SWAP (use sv-url)
  5. create let heroesPromise = getHeroes();
  6. We want to await the answer so let's use s-await-catch-block
  7. Move the UL and LI inside the :then

Emit a Save Event

  1. Add a Save button to HeroDetail
  2. on:click={saveHero}
  3. import { createEventDispatcher } from "svelte";
  4. use s-dispatch to get the func
  5. use s-dispatch-eventto dispatch('saveHero', hero)
  6. In HeroesList use on:saveHero={save}
  7. function save({detail: heroToSave}) { console.table{heroToSave}; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment