状态与绑定
在类组件中,每个字段只需声明一次。此编辑器一开始的标题为空,复选框未勾选,列表也为空。其颜色默认为黄色。
<import package="KScript.Web" />
<type name="NoteEditor" extends="Component">
<field name="title" type="string" />
<field name="done" type="bool" />
<field name="descriptions" type="string[]" />
<field name="color" type="color" default="'yellow'" />
<fn name="render">
<return value="```html
<label>Title <input @bind($title, on: blur)></label>
<label><input type="checkbox" @bind($done)> Done</label>
<button type="button" @on-click($title = ''; $done = false)>Clear</button>
```" />
</fn>
</type>import KScript.Web
type NoteEditor extends Component {
title: string
done: bool
descriptions: string[]
color: color = 'yellow'
fn render() {
return ```html
<label>Title <input @bind($title, on: blur)></label>
<label><input type="checkbox" @bind($done)> Done</label>
<button type="button" @on-click($title = ''; $done = false)>Clear</button>
```
}
}使用 <note-editor /> 挂载它,或使用 <note-editor title="First draft" /> 为其设置初始标题。数字从零开始,字符串从空文本开始,布尔值从 false 开始,集合从空列表或空映射开始。可为空的字段从 null 开始。为 color 等领域类型、枚举和记录提供有效的初始化器,或由调用方传入其值。像 enum NoteColor { red, blue } 这样的命名枚举会将编辑器的选项限制为其成员。
KScript 会在后续操作中恢复实例更改过的字段。组件只读取的字段可以在每次渲染时从调用方获取新值。浏览器只能提交带有匹配绑定的已渲染控件中的编辑内容。写入操作使用当前服务器会话进行授权。
在开始的 HTML 标签上使用指令来设置 KScript 的行为。例如,@bind($title, on: blur) 接受一个字段和选项,@live-disable() 是标志,@on-click($count += 1) 接受 KScript 语句。在 @ 之后,IDE 会补全指令名称,检查绑定名称,并检查每个选项的值。HTML 写法 bind="$title" 和 on-click="$count += 1" 同样有效。绑定通过 $ 指定其字段:@bind('title') 和 bind="title" 会报错,并提供快速修复为 @bind($title)。
每个指令、简写、修饰符和 $event 字段都列在 页面指令 中。
每个指令只有一种拼写。下面这些旧属性会报错,并附带快速修复,可将其移至现在的正确位置:
| 什么 | 现在 |
|---|---|
@bind-on(blur), bind-on="blur" |
@bind($draft, on: blur) |
live-confirm="Delete this note?" |
@on-click(delete: $note, confirm: 'Delete this note?') |
prevent-default="keydown" |
@on-keydown(save: $note, key: [ctrl, s], prevent: true) |
仅在需要时显示标签,或每个项目显示一次
@if 和 @each 直接写在标签本身上,因此单个标签不需要外层的 <if> 或 <for>:
<p @if($note)>{$note}</p>
<li @each($tasks, as: task, at: i)>{$i}. {$task.title}</li>
<li @each($tasks, as: task) @if(not $task.done)>{$task.title}</li>@if($cond)是围绕标签的<if test="$cond">:当它为假时,该标签不会出现在页面中。@show($cond)保留标签并将其隐藏,因此焦点和滚动位置得以保留。@each($list, as: name)为每个条目重复该标签,at: i用于指定位置,如<for each="name" in="$list" at="i">所示。若两者同时用在同一标签上,@each先运行,因此@if可以读取该条目。同时作用于多个标签时,请使用<if>和<for>。
在组件模板的顶层或直接位于 <live> 块内使用 <state name="…" value="…" />。使用 $name 读取,使用 $name = … 赋值。普通的状态值在该渲染块上的操作之后依然保留。
| 需要 | 标记 |
|---|---|
| 文本编辑 | <input @bind($draft)> |
| 现有的 map 字段 | <input @bind($draft.title)> |
| 一个等待 change 事件的编辑 | <input @bind($draft, on: change)> |
| 一个等待焦点离开后再提交的编辑框 | <input @bind($draft, on: blur)> |
| 随下一次操作一起发送的值 | <input @bind($draft, on: action)> |
| 停止输入后发送的值 | <input @bind($query, debounce: 300ms)> |
| 输入时修剪首尾空格 | <input @bind($name, trim: true)> |
| 作为类型读取的值(如果不是类型则拒绝) | <input type="number" @bind($age, as: int)>(string、int、number或bool) |
| 复选框 | <input type="checkbox" @bind($enabled)> |
| 一组单选按钮 | 为各个单选按钮设置相同的绑定,并为每个按钮分别指定自己的 value。 |
| 多个选定值 | 将 <select multiple> 绑定到一个列表。 |
| 可分享的 URL | <state name="page" value="1" query="page" /> |
| 在当前会话中跨访问保存的值 | <state name="filter" value="''" session="notes-filter" /> |
| 状态仅可由服务器操作写入 | <state name="owner_id" value="$owner.id" locked /> |
数字默认值使普通数字输入以数字形式更新状态。对于由查询参数支持的状态,请使用文本、数字、布尔值或 null 值。更改会更新当前的历史记录条目,而 null 会清除该参数。应保持独立的、基于会话的实例需要单独的键。
对于数据库分页,将当前页保存在由查询参数支持的状态中,在模型查询上调用 ->paginate(page: $page),并通过“下一页”和“上一页”按钮切换页码。视图可以使用 has_more 和当前页,在边界处禁用这些按钮。
使用 construct 定义输入与状态
默认情况下,页面可以设置组件的每个已存储字段。添加 construct 代码块,列出页面可以传递的属性。其他所有字段则成为组件自身的状态,从页面传递这些字段会报错。
<import package="KScript.Web" />
<type name="NoteCard" extends="Component">
<construct>
<field name="title" type="string" />
<field name="open" type="bool" default="false" />
<do>.heading = .title->upper()</do>
</construct>
<field name="heading" type="string" />
<field name="clicks" type="int" />
<fn name="render">
<return value="```html
<article>
<h3>{$heading}</h3>
<button type="button" @on-click(toggle: $open)>{$open ? 'Hide' : 'Show'}</button>
<button type="button" @on-click(increment: $clicks)>Clicked {$clicks}</button>
</article>
```" />
</fn>
</type>import KScript.Web
type NoteCard extends Component {
construct({
title: string,
open: bool = false,
}) {
.heading = .title->upper()
}
heading: string
clicks: int
fn render() {
return ```html
<article>
<h3>{$heading}</h3>
<button type="button" @on-click(toggle: $open)>{$open ? 'Hide' : 'Show'}</button>
<button type="button" @on-click(increment: $clicks)>Clicked {$clicks}</button>
</article>
```
}
}<note-card title="Shopping" /> 可用,<note-card clicks="{5}" /> 由 kscript check 报告。列表之后的代码块是可选的。每次页面构建组件时它都会运行,并且在恢复已保存的状态之前执行,因此不要在其中进行写入操作。有关适用于所有类型的规则,请参阅 构造函数。
将字段或方法标记为 private,即可将其限定在组件内部:private clicks: int、private fn tally()。页面无法传递它,其他代码也无法读取或调用它。请参阅 私有字段和方法。
使用 @inject() 获取路由的记录
显示模型记录的组件可以从路由中获取该记录,这样页面就无需传递它。将输入的默认值设为 @inject():
<!-- _components/post-card.kscript -->
<import package="KScript.Web" />
<import path="../models/post.kscript" />
<type name="PostCard" extends="Component">
<construct>
<field name="post" type="Post" default="@inject()" />
</construct>
<fn name="render" value="```html
<h2>{$post.title}</h2>
```" />
</type>// _components/post-card.kscript
import KScript.Web
import "../models/post.kscript"
type PostCard extends Component {
construct({ post: Post = @inject() })
fn render() => ```html
<h2>{$post.title}</h2>
```
}<!-- routes.kscript -->
<KScript.Routes>
<Get path="/posts/{post}" view="posts/show" />
</KScript.Routes>// routes.kscript
import KScript.Http
Routes {
Get(path: /posts/{post}, view: 'posts/show')
}<!-- views/posts/show.html -->
<post-card />对 /posts/42 的请求只会查找一次文章 42,若未找到则返回 404,组件则获得该记录。当路由调用一个接收该文章的控制器 fn show(post: Post) => @view('posts/show') 时,效果相同:控制器与组件共享同一条记录。
| 页面写入的内容 | 组件获得的内容 |
|---|---|
<post-card post="{$post}" /> |
该记录。页面传递的内容始终优先。 |
/posts/{post} 上的 <post-card /> |
路由中 {post} 所指定的记录。 |
路由上有一个 Post 但使用了其他名称的 <post-card /> |
该记录,例如 fn show(article: Post)。 |
其他任何位置的 <post-card /> |
一个错误,指出缺失的输入。 |
@inject()根据输入的类型读取模型,根据输入的名称读取路由参数。- 当路径中的名称不同时,
@inject(from: article)会采用路由中的{article}。 - 仅包含数字的路由(例如带有
fn show(id: int)的/posts/{id})无法提供Post。请为模型指定参数名,或直接传递记录:<post-card post="{Post->find($id)}" />。键永远不会自动转换为记录,因此每个查询都应编写在其运行的位置。 @inject(can: read)在获取记录时会询问模型的 策略,如果用户无权读取该记录,则返回403。任何权限均可使用:@inject(can: update)。- 单独使用时,
@inject(Post)会在任何路由被响应的地方提供该路由的文章,例如页面或控制器调用的函数。 - 实时组件在每次更新时都会重新查找记录,因此记录永远不会发送到浏览器。
- 在窗口、文档或终端中没有路由,因此由调用方传递记录。
当模型带有策略时,在获取记录时询问它:
<!-- _components/post-card.kscript -->
<import package="KScript.Web" />
<import path="../models/post.kscript" />
<type name="PostCard" extends="Component">
<construct>
<field name="post" type="Post" default="@inject(can: read)" />
</construct>
<fn name="render" value="```html
<h2>{$post.title}</h2>
```" />
</type>// _components/post-card.kscript
import KScript.Web
import "../models/post.kscript"
type PostCard extends Component {
construct({ post: Post = @inject(can: read) })
fn render() => ```html
<h2>{$post.title}</h2>
```
}接收带有策略的模型却不做任何询问的 @inject(),会在编辑器中产生警告(KS5017)。
@inject() 可作为任何类型输入的默认值使用,而不仅限于组件。请参阅 构造函数。
属于组件的类型
仅由一个组件使用的类型、枚举、错误或模型可以放在该组件的代码块内。这样组件文件就包含了它所需的全部内容。
<import package="KScript.Web" />
<import package="KScript.Data" />
<type name="CommentThread" extends="Component">
<model name="Comment" with="Timestamps">
<field name="post_id" type="int" />
<field name="body" type="string(min: 1, max: 2000)" />
</model>
<type name="Draft">
<field name="body" type="string" default="''" />
</type>
<enum name="Order" values="newest, oldest" />
<construct>
<field name="post_id" type="int" />
<field name="order" type="Order" default="'newest'" />
</construct>
<field name="draft" type="Draft" default="Draft({ })" />
<fn name="add">
<do>Comment->create(post_id: .post_id, body: .draft.body)</do>
<do>.draft = Draft({ })</do>
</fn>
<fn name="render">
<return value="```html
<section>
<p>{Comment->where(post_id: $post_id)->count()} comments, {$order} first</p>
<input @bind($draft.body)>
<button type="button" @on-click($add)>Add</button>
</section>
```" />
</fn>
</type>import KScript.Web
import KScript.Data
type CommentThread extends Component {
model Comment extends Timestamps {
post_id: int
body: string(min: 1, max: 2000)
}
type Draft {
body: string = ''
}
enum Order { newest, oldest }
construct({ post_id: int, order: Order = 'newest' })
draft: Draft = Draft({ })
fn add() {
Comment->create(post_id: .post_id, body: .draft.body)
.draft = Draft({ })
}
fn render() {
return ```html
<section>
<p>{Comment->where(post_id: $post_id)->count()} comments, {$order} first</p>
<input @bind($draft.body)>
<button type="button" @on-click($add)>Add</button>
</section>
```
}
}组件内部的声明属于该文件。组件的字段和方法通过名称使用它,其他任何文件都无法使用,即使是导入该组件的文件也不行。当第二个文件需要它时,请将其移至单独的文件(types/draft.kscript、models/comment.kscript)并在两处导入。当文件引用了所导入组件内部的类型时,kscript check 会提示此情况。
只有组件可以用这种方式包含声明。嵌套声明无法访问组件的字段,并且不会被视为文件中的第二个类型,因此每个文件一个类型的规则依然成立。kscript db diff 和 kscript db status 会同时读取组件内部的模型以及 models 文件夹中的模型。