horee-gridb0.0.1

选择 · 活动单元格

表格中有三种不同的“选中”。刚开始容易混淆,先区分清楚。

名称外观含义API
行选择整行浅色,multi 时有勾选列作为操作对象选中的行(要付款的记录、要删除的行)getSelectedRows() · select()
活动单元格单元格边框接收键盘输入的单元格(Excel 的当前单元格)getActiveCell() · setActiveCell()
区域多个单元格组成的块复制 · 粘贴 · 清除的对象用户操作

此外还有一个“当前行”标记(setCurrent)。在上下结构(主表 · 明细)的页面中,用来在上方列表中标出下方正在显示的行。

selection.js
import { createGrid } from 'horee-grid'

const rows = Array.from({ length: 500 }, (_, i) => ({ id: i + 1, vendor: `供应商 ${i + 1}`, amount: (((i * 104729) % 9000) + 100) * 1000 }))

const grid = createGrid(host, {
  locale: 'zh',
  rowKey: 'id',
  selection: 'multi',
  columns: [
    { field: 'id', title: '编号', width: 70, align: 'center' },
    { field: 'vendor', title: '供应商', flex: 1 },
    { field: 'amount', title: '付款额', type: 'number', width: 140 }
  ],
  rows,
  onSelectionChange: picked => {
    const sum = picked.reduce((s, r) => s + r.amount, 0)
    out(`已选 ${picked.length} 条 · 合计 ${sum.toLocaleString()}`)
  },
  onRowDblClick: row => out(`${row.vendor} — 双击`)
})

toolbar.innerHTML = `
  <button data-a="pick">选择 3 · 5 · 8 号</button>
  <button data-a="go">跳到 400 号</button>
  <button data-a="clear">取消选择</button>
  <span class="ex-out">已选 0 条</span>`
toolbar.onclick = e => {
  const a = e.target.dataset.a
  if (a === 'pick') [3, 5, 8].forEach(key => grid.select(key, false))
  if (a === 'go') grid.setCurrent(400)
  if (a === 'clear') grid.clearSelection()
}
const out = text => (toolbar.querySelector('.ex-out').textContent = text)

行选择

createGrid(host, { columns, rows, rowKey: 'id', selection: 'multi' })
selection行为
'single'(默认)点击的一行
'multi'最前面出现勾选列。点击勾选框选择,表头勾选框选择所有可见行(筛选后)
'none'不选择行(活动单元格 · 区域照常)
grid.getSelectedRows()        // 选中行的数组
grid.select(1024)             // 按 rowKey 值选择。multi 时追加。滚动到可见位置
grid.select(1024, false)      // 不滚动
grid.clearSelection()

选中的行每次变化都会调用 onSelectionChange(rows)。用于显示选中条数和合计。

重新查询也保留选择

即使用 setRows 替换行,rowKey 值相同的行仍保持选中。在保存后重新查询的页面中,用户的选择不会丢失。

行点击事件

createGrid(host, {
  columns, rows,
  onRowClick: (row, ev) => showDetail(row),
  onRowDblClick: row => openEditor(row)
})

当前行

grid.setCurrent(row.id)   // 上下出现线条并滚动到可见位置

它与行选择互不影响。即使勾选了多行,“当前行”也只有一个。

活动单元格

grid.getActiveCell()                    // { row, column } 或 null
grid.setActiveCell(row, 'amount')       // 移动并滚动
grid.startEdit()                        // 开始编辑该单元格(不可编辑时返回 false)

用于保存后把用户带到出错的单元格。

const bad = rows.find(r => !r.account)
if (bad) {
  grid.setActiveCell(bad, 'account')
  grid.startEdit()
}

区域

用鼠标拖动,或用 Shift+点击 · Shift+方向键扩大。Ctrl+A 为全选。区域是复制、粘贴和 Delete 的对象。参见 复制 · 粘贴 · Excel。

滚动

grid.scrollToRow(0)                            // 滚动到显示顺序的第 0 行
grid.scrollToRow(grid.getViewRows().length - 1) // 滚动到最后