响应式

声明状态

Svelte 5 标志 Svelte 5

<script>
  let name = $state("张三");
</script>

<h1>你好 {name}</h1>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("x-name")
export class XName extends LitElement {
  @state()
  name = "张三";

  render() {
    return html`<h1>你好 ${this.name}!</h1>`;
  }
}

更新状态

Svelte 5 标志 Svelte 5

<script>
  let name = $state("张三");
  name = "李四";
</script>

<h1>你好 {name}</h1>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("x-name")
export class XName extends LitElement {
  @state()
  name = "张三";

  constructor() {
    super();
    this.name = "李四";
  }

  render() {
    return html`<h1>你好 ${this.name}!</h1>`;
  }
}

计算属性

Svelte 5 标志 Svelte 5

<script>
  let count = $state(10);
  const doubleCount = $derived(count * 2);
</script>

<div>{doubleCount}</div>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("double-count")
export class DoubleCount extends LitElement {
  @state()
  count = 10;

  render() {
    const doubleCount = this.count * 2;
    return html`<div>${doubleCount}</div>`;
  }
}

模板语法

最简模板

Svelte 5 标志 Svelte 5

<h1>你好,世界</h1>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("hello-world")
export class HelloWorld extends LitElement {
  render() {
    return html`<h1>你好,世界</h1>`;
  }
}

样式

Svelte 5 标志 Svelte 5

<h1 class="title">我是红色的</h1>
<button style="font-size: 10rem;">我是一个按钮</button>

<style>
  .title {
    color: red;
  }
</style>

Lit 标志 Lit

import { LitElement, html, css } from "lit";
import { customElement } from "lit/decorators.js";
import { styleMap } from "lit/directives/style-map.js";

@customElement("css-style")
export class CssStyle extends LitElement {
  static styles = css`
    .title {
      color: red;
    }
  `;

  render() {
    return html`
      <h1 class="title">我是红色的</h1>
      <button style=${styleMap({ fontSize: "10rem" })}>我是一个按钮</button>
    `;
  }
}

DOM循环

Svelte 5 标志 Svelte 5

<script>
  const colors = ["红", "绿", "蓝"];
</script>

<ul>
  {#each colors as color (color)}
    <li>{color}</li>
  {/each}
</ul>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
import { repeat } from "lit/directives/repeat.js";

@customElement("colors-list")
export class ColorsList extends LitElement {
  colors = ["红", "绿", "蓝"];

  render() {
    return html`
      <ul>
        ${repeat(
          this.colors,
          (color) => color,
          (color) => html`<li>${color}</li>`,
        )}
      </ul>
    `;
  }
}

点击事件

Svelte 5 标志 Svelte 5

<script>
  let count = $state(0);

  function incrementCount() {
    count++;
  }
</script>

<p>计数器: {count}</p>
<button onclick={incrementCount}>+1</button>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("x-counter")
export class XCounter extends LitElement {
  @state()
  count = 0;

  incrementCount() {
    this.count = this.count + 1;
  }

  render() {
    return html`
      <p>计数器: ${this.count}</p>
      <button @click=${this.incrementCount}>+1</button>
    `;
  }
}

DOM引用

Svelte 5 标志 Svelte 5

<script>
  let inputElement;

  $effect(() => {
    inputElement.focus();
  });
</script>

<input bind:this={inputElement} />

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state, query } from "lit/decorators.js";

@customElement("input-focused")
export class InputFocused extends LitElement {
  @query("input") inputEl;

  firstUpdated() {
    this.inputEl.focus();
  }

  render() {
    return html`<input type="text" />`;
  }
}

条件渲染

Svelte 5 标志 Svelte 5

<script>
  const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
  let lightIndex = $state(0);

  const light = $derived(TRAFFIC_LIGHTS[lightIndex]);

  function nextLight() {
    lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length;
  }
</script>

<button onclick={nextLight}>下一个灯</button>
<p>现在亮着的是: {light}</p>
<p>
  你应该
  {#if light === "红灯"}
    <span>停下</span>
  {:else if light === "黄灯"}
    <span>慢行</span>
  {:else if light === "绿灯"}
    <span>赶紧走</span>
  {/if}
</p>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { choose } from "lit/directives/choose.js";

const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];

@customElement("traffic-light")
export class TrafficLight extends LitElement {
  @state()
  lightIndex = 0;

  get light() {
    return TRAFFIC_LIGHTS[this.lightIndex];
  }

  nextLight() {
    this.lightIndex = (this.lightIndex + 1) % TRAFFIC_LIGHTS.length;
  }

  render() {
    return html`
      <button @click=${this.nextLight}>下一个灯</button>
      <p>现在亮着的是: ${this.light}</p>
      <p>
        你应该
        ${choose(this.light, [
          ["红灯", () => html`<span>停下</span>`],
          ["黄灯", () => html`<span>慢行</span>`],
          ["绿灯", () => html`<span>赶紧走</span>`],
        ])}
      </p>
    `;
  }
}

生命周期

组件加载时

Svelte 5 标志 Svelte 5

<script>
  let pageTitle = $state("");
  $effect(() => {
    pageTitle = document.title;
  });
</script>

<p>页面标题: {pageTitle}</p>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("page-title")
export class PageTitle extends LitElement {
  @state()
  pageTitle = "";

  connectedCallback() {
    super.connectedCallback();
    this.pageTitle = document.title;
  }

  render() {
    return html`<p>页面标题: ${this.pageTitle}</p>`;
  }
}

组件卸载时

Svelte 5 标志 Svelte 5

<script>
  let time = $state(new Date().toLocaleTimeString());

  $effect(() => {
    const timer = setInterval(() => {
      time = new Date().toLocaleTimeString();
    }, 1000);

    return () => clearInterval(timer);
  });
</script>

<p>当前时间: {time}</p>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("x-time")
export class XTime extends LitElement {
  @state()
  time = "";

  timer;

  connectedCallback() {
    super.connectedCallback();
    this.timer = setInterval(() => {
      this.time = new Date().toLocaleTimeString();
    }, 1000);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    clearInterval(this.timer);
  }

  render() {
    return html`<p>当前时间: ${this.time}</p>`;
  }
}

组件组合

组件Props传参

Svelte 5 标志 Svelte 5

<script>
  import UserProfile from "./UserProfile.svelte";
</script>

<UserProfile
  name="张三"
  age={20}
  favouriteColors={["green", "blue", "red"]}
  isAvailable
/>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";

import "./user-profile";

@customElement("x-app")
export class XApp extends LitElement {
  render() {
    return html`<user-profile
      name="张三"
      age="20"
      .favouriteColors=${["green", "blue", "red"]}
      isAvailable
    ></user-profile>`;
  }
}

向父组件emit事件

Svelte 5 标志 Svelte 5

<script>
  import AnswerButton from "./AnswerButton.svelte";

  let isHappy = $state(true);

  function onAnswerNo() {
    isHappy = false;
  }

  function onAnswerYes() {
    isHappy = true;
  }
</script>

<p>你快乐吗?</p>
<AnswerButton onYes={onAnswerYes} onNo={onAnswerNo} />
<p style="font-size: 50px;">{isHappy ? "😀" : "😥"}</p>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

import "./answer-button";

@customElement("x-app")
export class XApp extends LitElement {
  @state()
  isHappy = true;

  onAnswerNo() {
    this.isHappy = false;
  }

  onAnswerYes() {
    this.isHappy = true;
  }

  render() {
    return html`
      <p>你快乐吗?</p>
      <answer-button
        @yes=${this.onAnswerYes}
        @no=${this.onAnswerNo}
      ></answer-button>
      <p style="font-size: 50px;">${this.isHappy ? "😀" : "😥"}</p>
    `;
  }
}

slot插槽

Svelte 5 标志 Svelte 5

<script>
  import FunnyButton from "./FunnyButton.svelte";
</script>

<FunnyButton>点我!</FunnyButton>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";

import "./funny-button";

@customElement("x-app")
export class XApp extends LitElement {
  render() {
    return html`<funny-button>点我!</funny-button>`;
  }
}

slot插槽内容

Svelte 5 标志 Svelte 5

<script>
  import FunnyButton from "./FunnyButton.svelte";
</script>

<FunnyButton />
<FunnyButton>这是传到slot的内容!</FunnyButton>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";

import "./funny-button";

@customElement("x-app")
export class XApp extends LitElement {
  render() {
    return html`
      <funny-button></funny-button>
      <funny-button>这是传到slot的内容!</funny-button>
    `;
  }
}

上下文

Svelte 5 标志 Svelte 5

<script>
  import { setContext } from "svelte";
  import UserProfile from "./UserProfile.svelte";
  import createUserState from "./createUserState.svelte.js";

  const user = createUserState({
    id: 1,
    username: "abcdefg",
    email: "[email protected]",
  });

  setContext("user", user);
</script>

<h1>欢迎回来, {user.username}</h1>
<UserProfile />

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { ContextProvider } from "@lit/context";

import { userContext } from "./user-context";

import "./user-profile";

@customElement("x-app")
export class XApp extends LitElement {
  @state()
  user = {
    id: 1,
    username: "abcdefg",
    email: "[email protected]",
  };

  provider = new ContextProvider(this, {
    context: userContext,
    initialValue: this.user,
  });

  updateUsername(newUsername) {
    this.user = { ...this.user, username: newUsername };
    this.provider.setValue(this.user);
  }

  render() {
    return html` <h1>欢迎回来, ${this.user.username}</h1>
      <user-profile
        .user="${this.user}"
        .updateUsername=${this.updateUsername.bind(this)}
      ></user-profile>`;
  }
}

表单输入

输入框

Svelte 5 标志 Svelte 5

<script>
  let text = $state("你好世界");
</script>

<p>{text}</p>
<input bind:value={text} />

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("input-hello")
export class InputHello extends LitElement {
  @state()
  text = "你好世界";

  handleInput(event) {
    this.text = event.target.value;
  }

  render() {
    return html`
      <p>${this.text}</p>
      <input value=${this.text} @input=${this.handleInput} />
    `;
  }
}

复选框

Svelte 5 标志 Svelte 5

<script>
  let isAvailable = $state(false);
</script>

<input id="is-available" type="checkbox" bind:checked={isAvailable} />
<label for="is-available">这是一个checkbox</label>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("is-available")
export class IsAvailable extends LitElement {
  @state()
  isAvailable = false;

  handleChange() {
    this.isAvailable = !this.isAvailable;
  }

  render() {
    return html`
      <input
        id="is-available"
        type="checkbox"
        ?checked=${this.isAvailable}
        @change=${this.handleChange}
      />
      <label for="is-available">这是一个checkbox</label>
    `;
  }
}

单选框

Svelte 5 标志 Svelte 5

<script>
  let picked = $state("red");
</script>

<div>你选择了: {picked}</div>

<input id="blue-pill" bind:group={picked} type="radio" value="blue" />
<label for="blue-pill">蓝色</label>

<input id="red-pill" bind:group={picked} type="radio" value="red" />
<label for="red-pill">红色</label>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";

@customElement("pick-pill")
export class PickPill extends LitElement {
  @state()
  picked = "red";

  handleChange(event) {
    this.picked = event.target.value;
  }

  render() {
    return html`
      <div>你选择了: ${this.picked}</div>

      <input
        id="blue-pill"
        name="pill"
        ?checked=${this.picked === "blue"}
        type="radio"
        value="blue"
        @change=${this.handleChange}
      />
      <label for="blue-pill">蓝色</label>

      <input
        id="red-pill"
        name="pill"
        ?checked=${this.picked === "red"}
        type="radio"
        value="red"
        @change=${this.handleChange}
      />
      <label for="red-pill">红色</label>
    `;
  }
}

选择器

Svelte 5 标志 Svelte 5

<script>
  let selectedColorId = $state(2);

  const colors = [
    { id: 1, text: "红" },
    { id: 2, text: "蓝" },
    { id: 3, text: "绿" },
    { id: 4, text: "灰", isDisabled: true },
  ];
</script>

<select bind:value={selectedColorId}>
  {#each colors as color}
    <option value={color.id} disabled={color.isDisabled}>
      {color.text}
    </option>
  {/each}
</select>

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { repeat } from "lit/directives/repeat";

@customElement("color-select")
export class ColorSelect extends LitElement {
  colors = [
    { id: 1, text: "红" },
    { id: 2, text: "蓝" },
    { id: 3, text: "绿" },
    { id: 4, text: "灰", isDisabled: true },
  ];

  @state()
  selectedColorId = 2;

  handleChange(event) {
    this.selectedColorId = event.target.value;
  }

  render() {
    return html`
      <select @change=${this.handleChange}>
        ${repeat(
          this.colors,
          (color) => color.id,
          (color) =>
            html`<option
              value=${color.id}
              ?selected=${this.selectedColorId === color.id}
              ?disabled=${color.isDisabled}
            >
              ${color.text}
            </option>`,
        )}
      </select>
    `;
  }
}

Web应用特性

渲染应用

Svelte 5 标志 Svelte 5

<!doctype html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./app.js"></script>
  </body>
</html>

Lit 标志 Lit

<!doctype html>
<html>
  <head>
    <script type="module" src="./app.js"></script>
  </head>

  <body>
    <x-app />
  </body>
</html>

fetch获取数据

Svelte 5 标志 Svelte 5

<script>
  import useFetchUsers from "./useFetchUsers.svelte.js";

  const response = useFetchUsers();
</script>

{#if response.isLoading}
  <p>正在获取用户信息……</p>
{:else if response.error}
  <p>获取用户信息出错</p>
{:else if response.users}
  <ul>
    {#each response.users as user}
      <li>
        <img src={user.picture.thumbnail} alt="user" />
        <p>
          {user.name.first}
          {user.name.last}
        </p>
      </li>
    {/each}
  </ul>
{/if}

Lit 标志 Lit

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
import { createFetchUsersTask } from "./fetch-users-task";

@customElement("x-app")
export class XApp extends LitElement {
  fetchUsers = createFetchUsersTask(this);

  render() {
    return this.fetchUsers.render({
      pending: () => html`<p>正在获取用户信息……</p>`,
      error: (e) => html`<p>获取用户信息出错</p>`,
      complete: (data) => html`
        <ul>
          ${data.map(
            (user) => html`
              <li>
                <img src=${user.picture.thumbnail} alt="user" />
                <p>${user.name.first} ${user.name.last}</p>
              </li>
            `,
          )}
        </ul>
      `,
    });
  }
}