svelte教程(4)邏輯

條件邏輯

有條件的渲染一些元素,使用 "if" 代碼塊:

<script>
    let user = { loggedIn: true };

    function toggle() {
        user.loggedIn = !user.loggedIn;
    }
</script>

{#if user.loggedIn}
    <button on:click={toggle}>
        Log out
    </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} is greater than 10</p>
{:else if 5 > x}
    <p>{x} is less than 5</p>
{:else}
    <p>{x} is between 5 and 10</p>
{/if}

循環邏輯

each 可以遍歷數組、類數組對象、以及可迭代對象 each [...iterable]。

<script>
  let list = [{ name: "aaa" }, { name: "bbb" }, { name: "ccc" }];
</script>

{#each list as l}
  <p>This is {l.name}</p>
{/each}

使用list爲空時渲染else代碼塊裏的內容。

<script>
  let list = [];
</script>
{#each list as l}
  <p>This is {l.name}</p>
{:else}
  <p>The list is empty</p>
{/each}

默認情況下,修改each塊的值時,它將在塊的末尾添加和刪​​除項目,並更新所有已更改的值。那可能不是您想要的。看下面一個例子,你會發現刪除掉的是最後一個元素,然而我們實際想要刪除的是第一個。

// Thing.svelte
<script>
    // `current` is updated whenever the prop value changes...
    export let current;

    // ...but `initial` is fixed upon initialisation
    const initial = current;
</script>

<p>
    <span style="background-color: {initial}">initial</span>
    <span style="background-color: {current}">current</span>
</p>

<style>
    span {
        display: inline-block;
        padding: 0.2em 0.5em;
        margin: 0 0.2em 0.2em 0;
        width: 4em;
        text-align: center;
        border-radius: 0.2em;
        color: white;
    }
</style>
<script>
  import Thing from "../components/Thing";
  let things = [
    { id: 1, color: "#0d0887" },
    { id: 2, color: "#6a00a8" },
    { id: 3, color: "#b12a90" },
    { id: 4, color: "#e16462" },
    { id: 5, color: "#fca636" }
  ];
  function handleClick() {
    things = things.slice(1);
  }
</script>

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

{#each things as thing}
    <Thing current={thing.color}/>
{/each}

爲了能夠刪除掉指定的元素,我們需要給元素加上唯一標識key:

<script>
  import Thing from "../components/Thing";
  let things = [
    { id: 1, color: "#0d0887" },
    { id: 2, color: "#6a00a8" },
    { id: 3, color: "#b12a90" },
    { id: 4, color: "#e16462" },
    { id: 5, color: "#fca636" }
  ];
  function handleClick() {
    things = things.slice(1);
  }
</script>

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

{#each things as thing (thing.id)}
    <Thing current={thing.color}/>
{/each}

有時我們還需要用到索引

// Thing.svelte
<script>
    // `current` is updated whenever the prop value changes...
    export let current;
  export let index;
    // ...but `initial` is fixed upon initialisation
    const initial = current;
</script>

<p>
    <span style="background-color: {initial}">initial {index}</span>
    <span style="background-color: {current}">current {index}</span>
</p>

<style>
    span {
        display: inline-block;
        padding: 0.2em 0.5em;
        margin: 0 0.2em 0.2em 0;
        width: 4em;
        text-align: center;
        border-radius: 0.2em;
        color: white;
    }
</style>
<script>
  import Thing from "../components/Thing";
  let things = [
    { id: 1, color: "#0d0887" },
    { id: 2, color: "#6a00a8" },
    { id: 3, color: "#b12a90" },
    { id: 4, color: "#e16462" },
    { id: 5, color: "#fca636" }
  ];
  function handleClick() {
    things = things.slice(1);
  }
</script>

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

{#each things as thing, i (thing.id)}
    <Thing current={thing.color} index={i}/>
{/each}

異步數據

svelte還可以處理異步數據。

<script>
  let num = 0;
  let promise = getNumber();
  function sleep(duration) {
    return new Promise(function(resolve, reject) {
      setTimeout(resolve, duration);
    });
  }
  async function getNumber() {
    await sleep(3000)
    if (num < 10) {
      return num;
    } else {
      throw new Error(`The ${num} is too big`);
    }
  }
  function handleClick() {
    num += 1;
    promise = getNumber();
  }
</script>

<button on:click={handleClick}>btn</button>
{#await promise}
  <p>...waiting</p>
{:then value}
  <p>The number is {value}</p>
{:catch error}
  <p style="color: red">{error}</p>
{/await}

如果在promise resolve調用之前不希望現實任何數據:

{#await promise then value}
  <p>The number is {value}</p>
{:catch error}
  <p style="color: red">{error}</p>
{/await}

如果確定不會執行reject,可以省略catch:

{#await promise then value}
  <p>The number is {value}</p>
{/await}

本教程的所有代碼均上傳到github有需要的同學可以參考 https://github.com/sullay/svelte-learn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章