You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用DataProvider时如何实现Vaadin Grid项数据绑定及行更新?

解决Vaadin Grid(Polymer3)远程数据模式下修改行数据不更新的问题

我明白你遇到的困扰了——当用dataProvider加载远程数据时,Vaadin Grid的items属性并不是你预想中存储已加载数据的数组,它在这里仅用来表示总数据量(和grid.size作用一致),所以直接尝试this.$.grid.items[0].firstName = 'changed'肯定不会生效,因为items根本不是实际的数据集。

要实现修改数据并让Grid同步更新,你需要完成两个核心操作:

  • 自行维护已加载数据的本地缓存
  • 修改缓存后通知Grid刷新对应的行

具体实现方案

调整你的代码,添加本地缓存存储分页数据,修改后调用Grid的刷新方法:

<vaadin-grid id="grid" aria-label="Remote Data Example">
 <vaadin-grid-column path="firstName"></vaadin-grid-column>
 <vaadin-grid-column path="lastName"></vaadin-grid-column>
 <vaadin-grid-column path="email"></vaadin-grid-column>
</vaadin-grid>
<script>
 window.addEventListener('WebComponentsReady', function() {
 const grid = document.querySelector('vaadin-grid');
 grid.size = 200;
 // 新增本地缓存,用"页码-每页条数"作为键存储对应页的数据
 const cachedPages = new Map();

 grid.dataProvider = function(params, callback) {
   const cacheKey = `${params.page}-${params.pageSize}`;
   // 优先从缓存取数据,避免重复请求远程接口
   if (cachedPages.has(cacheKey)) {
     callback(cachedPages.get(cacheKey));
     return;
   }

   var xhr = new XMLHttpRequest();
   xhr.onload = function() {
     const pageData = JSON.parse(xhr.responseText).result;
     // 将加载完成的页数据存入缓存
     cachedPages.set(cacheKey, pageData);
     callback(pageData);
   };
   var index = params.page * params.pageSize;
   xhr.open('GET', 'https://demo.vaadin.com/demo-data/1.0/people?index=' + index + '&count=' + params.pageSize, true);
   xhr.send();
 };

 // 示例:修改第一页第一条数据并触发刷新
 // 这里用setTimeout确保第一页数据已加载完成,实际场景可根据业务逻辑时机触发
 setTimeout(() => {
   const defaultPageSize = grid.pageSize; // 默认每页10条,可根据你的配置调整
   const firstPageKey = `0-${defaultPageSize}`;
   if (cachedPages.has(firstPageKey)) {
     const firstPageItems = cachedPages.get(firstPageKey);
     // 修改本地缓存中的数据
     firstPageItems[0].firstName = 'changed';
     // 通知Grid精准刷新这一行,传入修改后的item对象即可
     grid.refreshItem(firstPageItems[0]);
   }
 }, 1000);
 });
</script>

关键细节说明

  1. 本地缓存的必要性
    使用dataProvider时,Grid会按需请求分页数据,不会自动保存所有加载过的内容,所以必须自己维护缓存才能定位到要修改的条目。

  2. Grid刷新的正确方式

    • grid.refreshItem(item):这是最可靠的刷新方式,Grid通过对象引用来识别行,传入修改后的item就能精准刷新对应行,不会影响其他数据。
    • 若找不到具体的item对象,也可使用grid.refreshRow(rowIndex),但注意这里的rowIndex是Grid当前可见行的索引,不是全局数据的索引,仅在行确定可见时适用。
  3. 关于items属性的误区
    在远程数据模式(使用dataProvider)下,grid.items仅用来设置或获取总数据量,和grid.size功能等价,所以你看到它返回数字而非数组是正常的设计逻辑。

内容的提问来源于stack exchange,提问作者Hyyan Abo Fakher

火山引擎 最新活动