表单处理
在前面的引用属性文档中,我们已经初步了解了通过 &
语法获取变量引用的基本用法。在实际开发中,表单元素的值往往需要与状态变量保持同步,因此在表单处理场景中,引用属性显得尤为重要。本节将聚焦于表单元素的引用属性使用细节,介绍如何借助这一机制高效地获取和控制表单数据,实现响应性的数据绑定与更新。
文本输入
在引用属性文档的表单输入处理部分中,我们介绍了如何在 input
标签上使用 &value
引用属性实现输入内容与嵌入脚本变量值间的同步。类似地,textarea
标签同样支持相同的用法:
qk
<lang-js>
let inputValue = "Initial value"
</lang-js>
<p>The inputValue is: {inputValue}</p>
<textarea &value={inputValue}></textarea>
选择框
对于单选框与复选框,我们可以为其添加 &chcked
以同步选中状态与变量值:
qk
<lang-js>
let radioChecked = false
let checkboxChecked = false
</lang-js>
<input
type="radio"
&checked={radioChecked}
/>
<input
type="checkbox"
&checked={checkboxChecked}
/>
<p>radio: {radioChecked ? "" : "not"} checked</p>
<p>checkbox: {checkboxChecked ? "" : "not"} checked</p>
复选框组合
有时你可能需要同步多个复选框的状态,这可以通过多种方式实现,其核心思路是为每个复选框的 &checked
属性传入不同的目标:
- js
- ts
qk
<lang-js>
const checkedArr = []
const choices = ["Qingkuai", "Javascript", "Typescript"]
</lang-js>
<spread #for={item, index of choices}>
<input
type="checkbox"
!id={"choice" + item}
&checked={checkedArr[index]}
/>
<label
!for={"choice" + item}
style="margin-right: 20px;"
>
{item}
</label>
</spread>
<spread #for={item, index of choices}>
<p>{item}: {checkedArr[index] ? "" : "not"} checked</p>
</spread>
qk
<lang-ts>
const checkedArr: boolean[] = []
const choices = ["Qingkuai", "Javascript", "Typescript"]
</lang-ts>
<spread #for={item, index of choices}>
<input
type="checkbox"
!id={"choice" + item}
&checked={checkedArr[index]}
/>
<label
!for={"choice" + item}
style="margin-right: 20px;"
>
{item}
</label>
</spread>
<spread #for={item, index of choices}>
<p>{item}: {checkedArr[index] ? "" : "not"} checked</p>
</spread>
如果要同步多个选择框的选择状态,可以使用 &group
属性,并传入
选择器
select 选择器标签可接受 &value
引用属性:
qk
<lang-js>
let selected = "Typescript"
const choices = ["QingKuai", "Javascript", "Typescript"]
</lang-js>
<select &value={selected}>
<option
!value={item}
#for={item of choices}
>
{item}
</option>
</select>
<p>Your selected: {selected}</p>
如果是支持多选的 select,可以为它的 &value
属性传入一个 Array 或 Set,此时目标可以是常量,因为 qingkuai 只会调用它的方法而不会修改它本身:
qk
<lang-js>
const selectedItems = ["QingKuai", "Typescript"]
const choices = ["QingKuai", "Javascript", "Typescript"]
</lang-js>
<select
multiple
&value={selectedItems}
>
<option
!value={item}
#for={item of choices}
>
{item}
</option>
</select>
<p>Selected items: {selectedItems.join(", ")}</p>
我们更推荐使用 Set 集合,因为它在生成代码中的性能更好:
qk
<lang-js>
const selectedItems = new Set(["QingKuai", "Typescript"])
const choices = ["QingKuai", "Javascript", "Typescript"]
</lang-js>
<select
multiple
&value={selectedItems}
>
<option
!value={item}
#for={item of choices}
>
{item}
</option>
</select>
<p>Selected items: {Array.from(selectedItems).join(", ")}</p>