<!--
source: https://blueos.niceshare.site/guide/data-list-events/
site: 蓝河文档馆
summary: 在 data 里声明响应式字段，用 for / if 渲染，用 onclick 处理点击。
-->
---
title: 数据、列表与事件
description: 在 data 里声明响应式字段，用 for / if 渲染，用 onclick 处理点击。
---

这篇把数据绑定、列表和点击串成一个可运行的小页。待办应用会直接用这些写法。

**学完能做什么：** 写出会更新的文本、带 `tid` 的列表、以及不含 `{{ }}` 的事件绑定。

**前置：** [布局与样式](/guide/layout-and-style/)。

## 响应式数据

字段必须先在 `data` 里声明，或 `this.$set(key, value)`。改对象/数组的嵌套字段可能不刷新界面，应整表赋值：`this.todos = nextTodos`。

详见 [数据绑定](/reference/app-service/data-binding/)。

## 列表

`for` 的两项写法里，**下标在前**：`for="{{(index, item) in list}}"`。有稳定 id 时加 `tid`，好让节点复用。长列表用 [`<list>`](/component/container/list/) + [`<list-item>`](/component/container/list-item/)（`list-item` 的 `type` 必填，同 type 必须同结构）。

详见 [列表渲染](/reference/app-service/for/)、[条件渲染](/reference/app-service/if-show/)。

## 事件

写 `onclick="handler"` 或 `onclick="handler(item)"`。循环变量按名字解析。**不要** `onclick="handler({{ item }})"`。

详见 [事件处理](/reference/app-service/event-on/)。

## 完整示例

```html
<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` → 界面更新」。

## 本页要点

- 新字段进 `data` 或 `$set`；嵌套更新请赋新数组/对象。
- `for` 是 `(index, item)`；列表项加 `tid`。
- 事件绑定里不出现 `{{ }}`。

下一篇：[做一个待办应用](/guide/todo-app/)
