rust yew使用教程(一)

3 篇文章 0 订阅
本文档详细介绍了如何使用Rust的Yew框架创建Web应用,包括项目初始化、添加依赖、构建HTML结构、实现JS互调功能以及热更新。通过实例展示了Rust调用JSAPI的方法,并提供了项目运行和打包的步骤。Yew支持类似Vue和React的热更新,简化了开发者的工作流程。
摘要由CSDN通过智能技术生成
序言

    通过官方例子了解项目创建,热更新,以及编译,新版本的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的功能的服务,欢迎大家尝试。

Rust 中使用 Yew 框架编写 Function Component 非常简单。Function Component 是一种无状态组件,只接收 props 参数并返回一个 Virtual DOM 树。 下面是一个简单的例子,演示如何编写一个 Function Component: ```rust use yew::prelude::*; fn function_component(props: &Props) -> Html { html! { <div> <h1>{ props.title }</h1> <p>{ props.content }</p> </div> } } #[derive(Clone, PartialEq, Properties)] struct Props { title: String, content: String, } ``` 在这个例子中,我们定义了一个名为 `function_component` 的函数组件,并接受一个 `props` 参数。在函数组件中,我们使用 `html!` 宏来创建 Virtual DOM 树,并将 `props` 中的 `title` 和 `content` 属性设置为标题和段落的文本内容。 为了使用这个组件,我们需要在父组件中将 `Props` 传递给 `function_component` 函数,并将其渲染到页面上: ```rust use yew::prelude::*; struct App {} impl Component for App { type Message = (); type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { App {} } fn update(&mut self, _: Self::Message) -> ShouldRender { false } fn view(&self) -> Html { let props = Props { title: String::from("Hello, World!"), content: String::from("This is a Yew Function Component."), }; function_component(&props) } } ``` 在这个例子中,我们创建了一个名为 `App` 的组件,并在 `view` 方法中将 `Props` 传递给 `function_component` 函数。在实际应用中,我们可以根据需要设置不同的 `Props` 属性来渲染不同的页面内容。 希望这个例子对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值