脚本
GenUI的脚本部分使用Rust语言,在.gen文件中使用<script>标签进行包裹。
TIP
本文档仅简单说明脚本部分的使用,具体文档请参看:API
 
定义组件
对于自定义组件,我们需要使用#[component]宏进行组件的属性声明,但并不是所有的类型都是允许的,能够在属性中使用的类型需要实现Defaulttrait,
自定义struct和enum则需要使用#[prop]进行标注。
1<script>
2#[component]
3pub struct MyView{
4    name: String
5}
6</script>
 
定义组件属性
当你希望在组件中构建自定义结构体或枚举时,需要使用#[prop]进行标注并实现Default trait
1<script>
2#[component]
3pub struct MyView{
4    user: User,
5    auth: Auth
6}
7
8#[prop]
9#[derive(Debug, Clone)]
10pub struct User{
11    name: String
12}
13
14impl Default for User{
15    fn default() -> Self{
16        Self{ name: "John" }
17    }
18}
19
20#[prop]
21#[derive(Default, Clone, Copy, Debug)]
22pub enum Auth{
23    #[default]
24    Custom,
25    User,
26    Remote,
27    Other
28}
29</script>
 
定义组件的事件
本身自定义组件没有任何事件,事件需要使用#[event]宏进行声明,并且需要增加#[derive(Debug, Clone)]。
1#[event]
2#[derive(Debug, Clone)]
3pub enum MyViewEvent{
4    Clicked,
5    Changed(String),
6}
 
在上面的例子中,我们定义了两个事件回调:
Clicked 
Changed 
其中Clicked没有任何回调参数,Changed的回调参数为String类型。
数据绑定
在前面我们了解了如何定义组件的属性,而组件模版的数据绑定也是基于属性定义的
在这个例子中我们在MyView中定义了label的text属性的值,对于绑定的值,GenUI会自动生成对应的get和set方法。
1<template>
2    <component name="MyView">
3        <label id="my_label" :text="txt"></label>
4        <button id="my_btn" @clicked="change_txt()"></button>
5    </component>
6</template>
7
8<script>
9#[component]
10pub struct MyView{
11    txt: String
12}
13
14impl Default for MyView{
15    fn default() -> Self{
16        Self{
17            txt: "Hello".to_string()
18        }
19    }
20}
21</script>
 
在这段代码中,会自动生成get_txt和set_txt方法。
方法与回调
对于方法和回调而言需要使用impl定义在组件结构体内,以下例子中我们定义了change_txt方法作为按钮的点击的回调方法。
1<template>
2    <component name="MyView">
3        <label id="my_label" :text="txt"></label>
4        <button id="my_btn" @clicked="change_txt()"></button>
5    </component>
6</template>
7
8<script>
9#[component]
10pub struct MyView{
11    txt: String
12}
13
14impl Default for MyView{
15    fn default() -> Self{
16        Self{
17            txt: "Hello".to_string()
18        }
19    }
20}
21
22impl MyView{
23    fn change_txt(&mut self){
24        self.set_txt("World".to_string());
25    }
26}
27</script>