数据、列表与事件
本教程介绍 BlueOS 的响应式数据、列表渲染和事件绑定。完成后,页面可以渲染待办列表,并在选择列表项时更新标题。
- 已完成布局与样式。
- 已了解
.ux文件中<script>、<template>和<style>的作用。
声明响应式数据
Section titled “声明响应式数据”页面使用的响应式字段必须预先在 data 中声明,或通过 this.$set(key, value) 添加。直接修改对象或数组的嵌套字段无法可靠触发界面更新。更新集合时,应创建新值并重新赋值,例如 this.todos = nextTodos。
完整规则参见数据绑定。
for 的双变量语法将下标放在前面:for="{{(index, item) in list}}"。数据包含稳定的标识符时,应通过 tid 指定标识字段,以便运行时复用节点。
长列表应使用 <list> 和 <list-item>。list-item 必须声明 type,相同 type 的列表项必须具有相同结构。列表和条件语法参见列表渲染与条件渲染。
事件使用 onclick="handler" 或 onclick="handler(item)" 绑定。循环变量按名称解析,事件表达式中不得添加 {{ }}。
完整规则参见事件处理。
组合数据、列表和事件
Section titled “组合数据、列表和事件”- 打开首页的
index.ux。 - 将文件内容替换为以下代码:
<script> export default { data: { title: '今日任务', todos: [ { id: '1', title: '喝水' }, { id: '2', title: '散步' }, ], }, openItem(item) { this.title = item.title }, }</script>
<template> <div class="flex flex-col w-full"> <text class="text-white text-3xl">{{ title }}</text> <list class="w-full"> <list-item type="todo" for="{{(index, item) in todos}}" tid="id" onclick="openItem(item)"> <div class="flex items-center w-full"> <text class="text-white">{{ item.title }}</text> </div> </list-item> </list> </div></template>
<style>@tailwind utilities;</style>- 保存文件。
- 在模拟器中选择任意列表项。
页面顶部的标题应更新为所选待办的内容。这一结果说明对 data 中 title 的赋值触发了界面更新。
继续完成构建待办应用,将响应式数据、列表和事件与页面路由、本地存储及网络请求组合使用。