svelte教程(4)逻辑

简介: 条件逻辑有条件的渲染一些元素,使用 "if" 代码块:<script> let user = { loggedIn: true }; function toggle() { user.

条件逻辑

有条件的渲染一些元素,使用 "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。

目录
相关文章
|
人工智能 自然语言处理 算法
AI与API结合:自动解析商品描述+情感分析评论数据
AI与API深度融合正在重塑电商运营模式。通过自动解析商品描述、分析评论情感,企业可实现信息标准化、用户画像精准化及运营决策自动化。本文从技术架构、核心算法、实战案例三方面,详解AI如何驱动电商智能化升级。
|
存储 人工智能 缓存
AI变革药物研发:深势科技的云原生实践之路
阿里云助力深势科技推出创新的玻尔Bohrium®科研云平台和Hermite®药物计算设计平台,并持续完善。这两项先进的工业设计与仿真基础设施成果通过AI技术赋能科学研究和工业研发,不仅大幅缩短了药物研发周期,降低了成本,还显著提高了研发成功率,为生物医药行业带来了前所未有的变革,这是AI for Science领域的重大突破。
1310 38
|
数据库 对象存储
2025年 | 6月云大使推广奖励规则
云大使618活动上线。推荐首购达标,激励层层加码;月度消费达标,冲刺赢惊喜。最高可获得9万奖励;
|
存储 SQL BI
大型医院HIS,EMR,LIS,PACS源码
本产品支持信创,适用于三级及大中型医院,涵盖全面业务系统,助力医共体与单体医院发展。系统包括门诊和住院医生工作站、护士工作站、电子病历(EMR)、实验室信息系统(LIS)、放射科室管理(PACS/RIS)等模块,实现医院信息化建设目标。功能覆盖人性化服务、集成化管理、智能化操作、无纸化与无胶片化流程,优化医疗资源,提升医疗服务效率与质量,打造现代化数字医院。支持多系统接口与数据交换,满足医保需求,提供统计分析与权限管理,确保信息准确、安全、高效流转。
|
监控 Linux
Linux 运行进程实时监控pidstat命令详解
Linux 运行进程实时监控pidstat命令详解
643 0
|
XML 数据格式 Python
Python技巧:将HTML实体代码转换为文本的方法
在选择方法时,考虑到实际的应用场景和需求是很重要的。通常,使用标准库的 `html`模块就足以满足大多数基本需求。对于复杂的HTML文档处理,则可能需要 `BeautifulSoup`。而在特殊场合,或者为了最大限度的控制和定制化,可以考虑正则表达式。
957 12
|
存储 弹性计算 网络协议
阿里云服务器经济型e、通用算力型u1与c7/g7/r7/c8y/g8y/r8y实例区别及选择参考
在阿里云目前的各个活动中,除了轻量应用服务器之外,活动内的云服务器实例规格主要以经济型e、通用算力型u1、计算型c7/c8y、通用型g7/g8y、内存型r7/r8y这几个实例规格为主,c7/c8y属于计算型实例,g7/g8y属于通用型实例,c7/r8y属于内存型实例,c7/g7/r7属于最新第七代云服务器实例,c8y/g8y/r8y属于倚天云服务器实例,不同的云服务器实例规格在性能、特点及适用场景上有所不同,本文大家介绍一下阿里云服务器经济型e、通用算力型u1与c7/g7/r7/c8y/g8y/r8y的区别,以供参考。
阿里云服务器经济型e、通用算力型u1与c7/g7/r7/c8y/g8y/r8y实例区别及选择参考
|
JSON 缓存 Java
优雅至极!Spring Boot 3.3 中 ObjectMapper 的最佳实践
【10月更文挑战第5天】在Spring Boot的开发中,ObjectMapper作为Jackson框架的核心组件,扮演着处理JSON格式数据的核心角色。它不仅能够将Java对象与JSON字符串进行相互转换,还支持复杂的Java类型,如泛型、嵌套对象、集合等。在Spring Boot 3.3中,通过优雅地配置和使用ObjectMapper,我们可以更加高效地处理JSON数据,提升开发效率和代码质量。本文将从ObjectMapper的基本功能、配置方法、最佳实践以及性能优化等方面进行详细探讨。
1528 2
|
Windows
CMake 如何设置 Debug 和 Release 下的不同配置
CMake 设置 Debug 和 Release 下不同的工程依赖库,编译选项宏隔离等
2159 1
CMake 如何设置 Debug 和 Release 下的不同配置
|
开发工具 Android开发 git
Android自定义View——可以设置最大宽高的FrameLayout
Android自定义View——可以设置最大宽高的FrameLayout
1000 0

热门文章

最新文章