跳至主要內容
版本:0.21

建置範例 app

當你準備好環境後,你可以選擇使用包含 Yew 基本應用程式的樣板所需的樣板,或者手動建立一個小型專案。

使用樣板

安裝cargo-generate,請按照其安裝說明進行操作,然後執行以下指令

cargo generate --git https://github.com/yewstack/yew-trunk-minimal-template

手動設定應用程式

建立專案

首先,建立一個新的 cargo 專案。

cargo new yew-app

開啟新建立的目錄。

cd yew-app

執行 hello world 範例

若要驗證 Rust 環境的設定,請使用 cargo run 執行初始專案。你應該會看到「Hello World!」訊息。

cargo run
# output: Hello World!

將專案設定為 Yew 網路應用程式

要將這個簡單的命令列應用程式轉換成基本 Yew 網路應用程式,需要進行一些變更。

更新 Cargo.toml

yew 加入相依性清單。

[package]
name = "yew-app"
version = "0.1.0"
edition = "2021"

[dependencies]
# this is the development version of Yew
yew = { git = "https://github.com/yewstack/yew/", features = ["csr"] }
資訊

如果正在建置應用程式,你只需要 csr 功能。它會啟用 Renderer 和所有與用戶端渲染相關的程式碼。

如果正在製作程式庫,請勿啟用此功能,因為它會將用戶端渲染邏輯拉入伺服器端渲染程式包中。

如果需要 Renderer 來進行測試或範例,你應該在 dev-dependencies 中啟用它。

更新 main.rs

我們需要產生一個範本,設定一個名為 App 的根元件,用於呈現一個按鈕,並在按鈕被按一下時更新其值。將 src/main.rs 的內容替換為下列程式碼。

注意事項

main 函式中呼叫 yew::Renderer::<App>::new().render() 會啟動你的應用程式,並將其掛載到頁面的 <body> 標籤。如果你想要隨任何動態屬性啟動你的應用程式,可以改用 yew::Renderer::<App>::with_props(..).render()

use yew::prelude::*;

#[function_component]
fn App() -> Html {
let counter = use_state(|| 0);
let onclick = {
let counter = counter.clone();
move |_| {
let value = *counter + 1;
counter.set(value);
}
};

html! {
<div>
<button {onclick}>{ "+1" }</button>
<p>{ *counter }</p>
</div>
}
}

fn main() {
yew::Renderer::<App>::new().render();
}

建立 index.html

最後,在 app 根目錄中加入一個 index.html 檔案。

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
</head>
<body></body>
</html>

檢視你的網路應用程式

執行以下命令來在本地建置和執行應用程式。

trunk serve
資訊

加入 '--open' 選項來開啟你的預設瀏覽器 trunk serve --open

如果您修改它的任何原始碼檔案,Trunk 會重建您的應用程式。預設伺服器會偵聽位址「127.0.0.1」和連接埠「8080」=> https://127.0.0.1:8080。若要變更,請建立下列檔案並根據需要編輯

Trunk.toml
[serve]
# The address to serve on LAN.
address = "127.0.0.1"
# The address to serve on WAN.
# address = "0.0.0.0"
# The port to serve on.
port = 8000

恭喜

您現在已成功設定您的 Yew 開發環境,並建立您的第一個 Web 應用程式。

在此應用程式中做實驗並檢閱範例以進一步學習。