脚本

GenUI的脚本部分使用Rust语言,在.gen文件中使用<script>标签进行包裹。

TIP

本文档仅简单说明脚本部分的使用,具体文档请参看:API

定义组件属性

对于自定义组件,我们需要使用#[prop]宏进行组件的属性声明,但并不是所有的类型都是允许的,能够在属性中使用的类型需要实现Defaulttrait。

1<script>
2#[prop]
3pub struct MyView{
4    name: String
5}
6</script>

定义组件的事件

本身自定义组件没有任何事件,事件需要使用#[event]宏进行声明,并且需要增加#[derive(Debug, Clone)]

1#[event]
2#[derive(Debug, Clone)]
3pub enum MyViewEvent{
4    Clicked,
5    Changed(String),
6}

在上面的例子中,我们定义了两个事件回调:

  1. Clicked
  2. Changed

其中Clicked没有任何回调参数,Changed的回调参数为String类型。

数据绑定

在前面我们了解了如何定义组件的属性,而组件模版的数据绑定也是基于属性定义的

在这个例子中我们在MyView中定义了labeltext属性的值,对于绑定的值,GenUI会自动生成对应的getset方法。

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#[prop]
10pub struct MyView{
11    txt: String
12}
13
14let mut prop = default_prop!{
15    MyView{
16        txt: "Hello".to_string()
17    }
18};
19</script>

在这段代码中,会自动生成get_txtset_txt方法。

方法与回调

对于方法和回调而言使用fnclosure进行声明,以下例子中我们定义了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#[prop]
10pub struct MyView{
11    txt: String
12}
13
14let mut prop = default_prop!{
15    MyView{
16        txt: "Hello".to_string()
17    }
18};
19
20fn change_txt(){
21    prop.set_txt("World".to_string());
22}
23</script>

以上方法还可以使用closure来改写

1let mut change_txt = ||{
2    prop.set_txt("World".to_string());
3};