序言
通过官方例子了解项目创建,热更新,以及编译,新版本的yew比之前方便很多,有配套工具,可以做到类似vue与react这样热更新,实时查看自己代码,yew还可以调用外部js与内部调用js api等,官方文档-中文链接。
一、创建项目(注: trunk版本不用使用lib做为项目)
cargo new yew-app
二、在Cargo.toml文件中添加yew作为依赖项
[dependencies]
# 你可以在此处查看最新版本: https://crates.io/crates/yew
yew = "0.18"
三、在根目录下创建index.html(注:文件名和位置不能修改否则)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
</head>
</html>
四、src/js_api.rs
use yew::web_sys;
// 获取js windwos对象
pub fn get_js_window() -> web_sys::Window {
web_sys::window().expect("window not available")
}
pub fn js_alert(msg: &str) {
get_js_window().alert_with_message(msg).expect("alert failed");
}
五、src/main.rs
use yew::{prelude::*};
mod js_api;
enum Msg {
AddOne,
}
struct Model {
// `ComponentLink` is like a reference to a component.
// It can be used to send messages to the component
link: ComponentLink<Self>,
value: i64,
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
value: 0,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::AddOne => {
self.value += 1;
js_api::js_alert("hello from wasm!");
// the value has changed so we need to
// re-render for it to appear on the page
true
}
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
false
}
fn view(&self) -> Html {
html! {
<div>
<button onclick=self.link.callback(|_| Msg::AddOne)>{ "点击 +1" }</button>
<p>{ self.value }</p>
</div>
}
}
}
fn main() {
yew::start_app::<Model>();
}
安装环境与运行
如果尚未安装 Trunk,请执行以下操作:
cargo install trunk wasm-bindgen-cli
将wasm32-unknown-unknown添加为编译目标。 如果还未安装,请使用 Rustup 运行以下指令:
rustup target add wasm32-unknown-unknown
启动服务,端口为 ‘0.0.0.0:8080’,运行后会将编译文件放在/dist目录(注:如果之前运行后无法运行,删除/target目录重新编译即可)
trunk serve
项目打包
trunk build --release
总结
本文档只是借鉴官方示例演示yew项目如何创建与运行,其中有演示在rust中调用jsapi,但不仅限于此,rust也可以直接调用js代码的,当然由于篇幅限制不在此处展开,有兴趣的小伙伴可以去官方文档中找官方示例其中就包含此种方式;yew有两种运行方式,第一种是通过trunk,第二种是wasm-pack,后者不支持热更新,没有服务必须要自定义或者使用其它服务才能运行,总之后者比较繁琐,当然有能力的小伙伴也可以做到类似trunk的功能的服务,欢迎大家尝试。