handsontable表格添加删除按钮

249 阅读1分钟

个人查找到的添加按钮的方法

1. 在配置项的columns数组中添加相应对象

{
         title: "操作",
         data: '', // 操作列没有对应的数据字段
         renderer: 'buttonRenderer', // 使用自定义渲染器 这个一定要有
         className: 'htCenter htMiddle', // 设置表格居中
         readOnly: true, // 不设置这个属性双击按钮所在的单元格会进入编辑模式
      }

image.png

2. 自定义渲染器

  • instance: Handsontable 实例,用于访问和操作表格数据和设置。
  • td: 要渲染的单元格(HTML 的 元素)。
  • row: 当前单元格所在的行索引。
  • col: 当前单元格所在的列索引。
  • prop: 当前单元格的属性名称。
  • value: 当前单元格的值。
  • cellProperties: 当前单元格的属性。
function buttonRenderer(instance, td, row, col, prop, value, cellProperties) {
   // 创建点击按钮
   const button = document.createElement('button');
   // 为按钮设置样式
   button.innerHTML = '操作';
   button.style.padding = '10px 15px';
   button.style.fontSize = '12px';
   button.style.cursor = 'pointer';
   button.style.border = '0';
   button.className = 'btn btn-primary';
   // 为按钮添加点击事件
   button.addEventListener('click', () => {
    // 获取点击这行的数据
      const rowData = instance.getDataAtRow(row);
      const rowObject = {};
       /*
       使用 instance.getColHeader() 获取列头数组,并遍历每个列头:
       通过 hotSettings.columns[index].data 获取列的属性名 prop。
       将对应的行数据赋值给 rowObject[prop]。 
       */
      instance.getColHeader().forEach((header, index) => {
         const prop = hotSettings.columns[index].data;
         rowObject[prop] = rowData[index];
      });
      console.log('Row object:', rowObject);
   });
   td.innerHTML = '';
   td.appendChild(button);
}

3.注册自定义渲染器(这一步不是必须的,但是如果你想在 Handsontable 中多次复用这个自定义渲染器,那么将其注册为一个命名渲染器会很有用。)

    Handsontable.renderers.registerRenderer('buttonRenderer', buttonRenderer);

区别(注册组件)

image.png

不注册组件

image.png

4.页面

image.png

打印

image.png