第一个简单的 App
首先创建一个二进制项目:
1. cargo new --bin yew-app && cd yew-app
添加 yew 到你的依赖库中(这里 可以查看最新版本的 Yew)
Cargo.toml
1. [package]
2. name = "yew-app"
3. version = "0.1.0"
4. authors = ["Yew App Developer <[email protected]>"]
5. edition = "2018"
7. [dependencies]
8. yew = { version = "0.14.3", features = ["std_web"] }
将这份代码复制到你的 src/main.rs 文件中:
src/main.rs
1. use yew::prelude::*;
3. struct Model {
4. link: ComponentLink<Self>,
5. value: i64,
6. }
8. enum Msg {
9. AddOne,
10. }
12. impl Component for Model {
13. type Message = Msg;
14. type Properties = ();
15. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
16. Self {
17. link,
18. value: 0,
19. }
20. }
22. fn update(&mut self, msg: Self::Message) -> ShouldRender {
23. match msg {
24. Msg::AddOne => self.value += 1
25. }
26. true // 指示组件应该重新渲染
27. }
29. fn view(&self) -> Html {
30. html! {
31. <div>
32. <button onclick={self.link.callback(|_| Msg::AddOne)}>{ "+1" }</button>
33. <p>{ self.value }</p>
34. </div>
35. }
36. }
37. }
39. fn main() {
40. yew::initialize();
41. App::<Model>::new().mount_to_body();
42. }
这份代码将构建你的称为 Model 的 Component 根组件,它会显示一个按钮,当你点击它时,Model 将会更新自己的状态。特别注意 main() 中的 App::<Model>::new().mount_to_body(),它会启动你的应用并将其挂载到页面的 <body> 标签中。如果你想使用任何动态属性来启动应用程序,则可以使用 App::<Model>::new().mount_to_body_with_props(..)。
运行你的应用程序!
启动并运行你的应用的最快方式就是使用 cargo-web。如果你还没有的话,请用 cargo install cargo-web 命令来安装这个工具然后通过运行下述命令来构建和启动一个开发服务器:
1. cargo web start
cargo-web 将会自动为你添加 wasm32-unknown-unknown 作为目标代码,然后构建你的应用,你的应用将默认在 http://[::1]:8000 被访问。可以通过 cargo web start --help 命令来获取更多选项和帮助。
