Element:input 事件

当一个 input select 或 textarea 元素的 value 被修改时,会触发 input 事件。

事件的 target 为当前正在编辑的宿主。

每当元素的 value 改变,input 事件都会被触发。这与 change 事件不同。
change 事件仅当 value 被提交时触发,如按回车键,从一个 options 列表中选择一个值等。

示例:

<input placeholder="输入一些文本" name="name" />
<p id="values"></p>

<script>
const input = document.querySelector("input");
const log = document.getElementById("values");

input.addEventListener("input", updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}
</script>

对于input, 在Leptos中强调了 value attribute 和 value property 的区别。许多前端框架会混淆这两者。
https://book.leptos.dev/view/05_forms.html

attribute用来设置初始值,而property 则是设置当前值。就是当用户在 input界面上输入过之后,只能用 property来修改

打开浏览器的 about:blank 页面, 用 Ctrl + Shift + I 调出 调试界面,在 控制台里 依次 输入下面四句(输入完一句,看一下效果)

const el = document.createElement("input");
document.body.appendChild(el);

el.setAttribute("value", "test"); el.setAttribute("value", "another
test");

页面最后会出现一个 输入框
在 input框中输入几个字符,或者删除几个字符。

el.setAttribute("value", "one more time?");

再用 setAttribute 就无法改变 input的内容了,只能用prop

el.value = "But this works";

它不仅仅是一个 常量集合,而是一个代数数据类型(algebraic data type, ADT)。
它可以有多个变体(variant),而且每个变体可以携带不同的类型和不同的数量的数据。

enum Message {
    Quit,                       // 不带数据
    Move { x: i32, y: i32 },    // 带命名字段 (struct-like)
    Write(String),              // 带一个值(tuple-like)
    ChangeColor(i32, i32, i32), // 带多个值(tuple-like)
}

Leptos 和 Trunk 在底层捆绑了一段 JavaScript 代码,用于加载 Leptos UI。
该 UI 已被编译为 WebAssembly,用于驱动您的 CSR(客户端渲染)网站的交互。

如果您希望使用功能更齐全的模板---如何设置您在真实的 Leptos 项目中会看到的一些基础知识,例如路由(后面的章节会介绍)、将标签注入页面头部,Title以及Meta一些其他细节,那么请使用start-trunk模板库来启动和运行。

先安装 trunk 和 cargo-generate

cargo install trunk
cargo install cargo-generate

然后使用模板来初始化你的项目

cargo generate --git https://github.com/leptos-rs/start-trunk

最后运行

trunk serve --port 3000 --open

在新创建的应用目录中,开始开发您的应用。Trunk 服务器会在文件更改时重新加载您的应用,从而使开发过程相对无缝。

1)设置console_error_panic_hook

默认情况下,在浏览器中运行 WASM 代码时发生的panic只会在浏览器中抛出一个错误,并显示一条无用的消息Unreachable executed,和 指向 WASM 二进制文件的堆栈跟踪。

通过console_error_panic_hook,您可以得到 精确到 Rust 源代码中的某一行的Rust 堆栈跟踪。

设置起来非常简单:

(1)在您的项目的根目录下运行 cargo add console_error_panic_hook
(2)在您的main function中,添加console_error_panic_hook::set_once();

_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();


2) Editor Autocompletion inside #[component] and #[server]

由于宏的性质,rust-analyzer 很难做到正确的自动完成和其他支持。

如果您在编辑器中使用这些宏时遇到问题,可以明确指示 rust-analyzer 忽略某些 proc 宏。

尤其对于 #[server]这种 只 注释 (annotates)函数体但实际上并不转换函数体内部任何内容的宏来说,这非常有帮助。

从 Leptos 0.5.3 版本开始,rust-analyzer 已添加对#[component]宏的支持。但如果您遇到问题,可以将 #[component] 添加到宏忽略列表中。请注意,这意味着 rust-analyzer 无法识别您的组件 props,而props可能会在 IDE 中生成其自身的错误或警告。

如果你因为某些原因用的比较老的版本Leptos,可以像下面这样修改VSCode等IDE的设置

VSCode的settings.json

"rust-analyzer.procMacro.ignored": {
    "leptos_macro": [
        // optional:
        // "component",
        "server"
    ],
}

带 cargo-leptos 的 VSCode的settings.json

"rust-analyzer.procMacro.ignored": {
    "leptos_macro": [
        // optional:
        // "component",
        "server"
    ],
},
// if code that is cfg-gated for the `ssr` feature is shown as inactive,
// you may want to tell rust-analyzer to enable the `ssr` feature by default
//
// you can also use `rust-analyzer.cargo.allFeatures` to enable all features
"rust-analyzer.cargo.features": ["ssr"]



3) 与 Rust Analyzer 一起使用leptosfmt (可选设置)

leptosfmt是 Leptos 的 view!宏 的格式化程序(您通常会在宏里面编写 UI 代码)。由于该view!宏支持使用“RSX”(类似 JSX)风格编写 UI,因此 cargo-fmt 很难自动格式化宏内的代码view!。

leptosfmt是一个可以解决您的格式化问题并让您的 RSX 风格 UI 代码保持美观整洁的 crate!

leptosfmt可以通过命令行或代码编辑器安装和使用:

首先,安装该工具 cargo install leptosfmt

如果您只想使用命令行中的默认选项,只需从项目根目录运行

leptosfmt ./*/.rs

即可使用leptosfmt格式化所有 rust 文件。

与 Rust Analyzer 一起使用

(1) 在项目的根目录下放置 rustfmt.toml , 内容为

edition = "2021"

(2) 配置 Rust Analyzer

方法一:在项目的根目录下放置 rust-analyzer.toml, 内容为

[rustfmt]
overrideCommand = ["leptosfmt", "--stdin", "--rustfmt"]
# (optional) other config...

这种方法与你使用 什么编辑器无关,所以更值得推荐。
唯一需要注意的是, rust-analyzer的版本最好是 2024-06-10 之后

方法二:

对于 VSCode 用户,我建议使用工作区设置(CMD + shift + p -> 打开工作区设置),这样您只能leptosfmt为使用 leptos 的工作区进行配置。

打开您的工作区设置并添加以下配置:

{
  "rust-analyzer.rustfmt.overrideCommand": ["leptosfmt", "--stdin", "--rustfmt"]
}




在 leptosfmt.toml 可以设置其他选项

max_width = 100 # Maximum width of each line
tab_spaces = 4 # Number of spaces per tab
indentation_style = "Auto" # "Tabs", "Spaces" or "Auto"
newline_style = "Auto" # "Unix", "Windows" or "Auto"
attr_value_brace_style = "WhenRequired" # "Always", "AlwaysUnlessLit", "WhenRequired" or "Preserve"
macro_names = [ "leptos::view", "view" ] # Macro names which will be formatted
closing_tag_style = "Preserve" # "Preserve", "SelfClosing" or "NonSelfClosing"

# Attribute values can be formatted by custom formatters
# Every attribute name may only select one formatter (this might change later on)
[attr_values]
class = "Tailwind" # "Tailwind" is the only attribute value formatter available for now



4) 在开发过程中使用 --cfg=erase_components

Leptos 0.7 对渲染器进行了一些更改,使其更加依赖类型系统。对于较大的项目,这可能会导致编译时间变慢。
--cfg=erase_components 在开发过程中使用自定义配置标志可以缓解大部分编译时间的拖慢。
(这会删除一些类型信息,以减少编译器的工作量和调试信息,但会增加二进制文件大小和运行时开销,因此最好不要在release模式下使用。)

在命令行启用,就是运行trunk是带环境变量

RUSTFLAGS="--cfg erase_components" trunk serve

或者

RUSTFLAGS="--cfg erase_components" cargo leptos watch

又或者,直接在 .cargo/config.toml 进行配置

[target.wasm32-unknown-unknown]
rustflags = [
   "--cfg",
   "erase_components",
]

从上面这些来看, Leptos比sycamore更完善一些

  1. 安装rust

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

  2. 添加wasm编译器

    rustup target add wasm32-unknown-unknown

  3. 安装trunk

    cargo install trunk

  4. 新建项目

    cargo init leptos-tutorial
    cd leptos-tutorial
    cargo add leptos --features=csr

在项目的根目录创建 index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body></body>
</html>

用下面的内容替换src/main.rs

use leptos::prelude::*;

fn main() {
    leptos::mount::mount_to_body(|| view! { <p>"Hello, world!"</p> })
}

在项目的根目录运行

trunk serve --open

Trunk 会自动编译你的应用并在默认浏览器中打开它。