Aside from scripting (data processing), the other core point of a component is the UI.

But THE HTML used to describe the UI is a markup language, so HTML itself cannot express logic

Therefore, Svelte adds logical support for templates, such as judgment and traversal, to enhance the logical expression of the UI.

The characteristics of

  1. Svelte’s compiler will compile this logic by compiling the HTML into a form created using native JS, meaning that the HTML will eventually be created using a native DOM API like createElement.
  2. Logical identifier, commonly used{}To wrap,{#xxx}Represents the beginning of a logical block,{:xxx}Represents the continuation or transit of a logical block,{/xxx}Indicates the end of a logical block

conditional

if

{#if user.loggedIn}
  <button on:click={toggle}>Log out</button>
{/if}
Copy the code

if ... else ...

{#if user.loggedIn}
  <button on:click={toggle}>Log out</button>
{:else}
  <button on:click={toggle}>Log in</button>
{/if}
Copy the code

if ... else if ... else...

{#if x > 10}
  <p>{x} more than 10</p>
{:else if 5 > x}
  <p>{x} less than 5</p>
{:else}
  <p>{x} is between 5 and 10</p>
{/if}
Copy the code

cycle

Each block without key

<! -- each array as value, index -->
{#each cats as cat, i} <! {#each cats as {id, name}, I} -->
  <li>
    <a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
      {i + 1}:{cat.name}
    </a>
  </li>
{/each}
Copy the code

Provide each block of key

  1. Svlete is gonevirtual domSo keys in svelte are not involvedDOM DiffIn the
  2. Svelte does not add a key and does not report an error or warning
  3. By default, when you modifyeachBlock value when it will be the block’sThe end of theLocation adds and removes items and updates all changed values. But that’s probably not what you want.
  4. Key in sVELte also gives a unique ID to a component, so that sVELte can better identify each component object and update it
<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);
	console.log(things); 
        [{id: 2, name: 'banana'}, {id: 3, name: 'Carrot'}, {id: 4, name: 'doughnut' }, { id: 5, name: 'egg' } ] */
    }
</script>

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

<! -- each array as value, key (id) -->
{#each things as thing (thing.id)}
    <Thing name={thing.name}/>
{/each}

<! Svelte uses' map 'structure to bind key values. So in principle, any object can be used as a key in svelte 3. But it's recommended to use a string or a number for a key, because strings or numbers are usually safer, because they guarantee the unique immutability of the key whereas an object is a reference data type, and a key is just a reference, There's no guarantee that the attributes and values in the object that you're referring to won't change and that's why it's not recommended to use index as the key because if you insert an element in the middle, then all of the following elements will change their keys, 4. The purpose of the key is to make it easy for Svlete to calculate which elements are unchanged, so that it does not need to be recreated to reduce the DOM rendering effort -->
Copy the code

Render object length is zero

<script>
    let cats = []
</script>

<! If there is no content in the object to render, i.e. length is 0, then no content will be rendered in the corresponding position. So now the interface is empty and nothing has been rendered -->
{#each cats as cat, i} 
  <li>
    {i} --- {cat}
  </li>
{/each}
Copy the code

Await block

This is a logical block unique to Svelte

So that the Svelte program must process asynchronous data at some point

<script>
  // getRandomNumber is an asynchronous request that returns a Promise
  let getNumberPromise = getRandomNumber();
</script>

<! -- number is a promise returned by an asynchronous operation -->
{#await getNumberPromise}
    <! -- Pending operation -->
    <p>loading ...</p>
{:then number}
    <! Resolve (resolve); resolve (number);
    <p>{number}</p>
{:catch error}
    <! Reject (reject); error is the returned error object.
    <p>{error.message}</p>
{/await}
Copy the code
<! In many cases, we may not need to process pending or reject so we can abbreviate await blocks -->

<! -- omitting pending operation -->
{#await getNumberPromise then number}
    <p>{number}</p>
{:catch error}
    <p>{error.message}</p>
{/await}

<! Omit pending and reject processing of promise results
{#await getNumberPromise then number}
    <p>{number}</p>
{/await}
Copy the code

key

<script>
    let num = 0;
    let opacity = 1
	
    function addNumber() {
	opacity = 0
		
        // Fade out. Change the value of num and fade in
	setTimeout(() = > {
            num = num + 2
            opacity = 1
	}, 500)}</script>

<! Use transition to fade out and fade in num values
<p style="0.5 s help ease the transition: opacity; opacity: {opacity};">{ num }</p>
<button on:click="{addNumber}">+ 2</button>
Copy the code
<! Svlete encapsulates some simple animations in this example.
<script>
    import { fade } from 'svelte/transition';
    let num = 0;
</script>

<! It will fade only when the element is created, so there is no fade in and out effect when the key block is not wrapped. The function of the key block is the same as the function of the key in each block. When num changes, svelte will automatically destroy and re-create the P tag.
{#key num}
    <p in:fade>{ num }</p>
{/key}
<button on:click="{() => num += 2}">+ 2</button>
Copy the code