全部 / 前端 · 2023年6月6日 0

Ant-Design-Vue table 合并单元格,添加事件

官方给出了合并单元格的例子:

const columns = [
    {
      title: 'Home phone',
      colSpan: 2,
      dataIndex: 'tel',
      customRender: (value, row, index) => {
        const obj = {
          children: value,
          attrs: {},
        };
        if (index === 2) {
          obj.attrs.rowSpan = 2;
        }
        // These two are merged into above cell
        if (index === 3) {
          obj.attrs.rowSpan = 0;
        }
        if (index === 4) {
          obj.attrs.colSpan = 0;
        }
        return obj;
      },
    },
]

主要使用的是:customRender :

但是官方没有给出如何在合并单元格的情况下,且添加单击事件。经过尝试之后发现 customRender 返回的:

const obj = { children: value, attrs: {}, };

其中的 children 可以借助 createElement 返回一个 VNode 的形式:

render:function(createElement){
    return 
        // @returns {VNode}
        createElement(
          // {String | Object | Function}
          // 一个 HTML 标签名、组件选项对象,或者
          // resolve 了上述任何一种的一个 async 函数。必填项。
          "div",

          // {Object}
          // 一个与模板中 attribute 对应的数据对象。可选。
          {
            // (详情见下一节)
          },

          // {String | Array}
          // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成,
          // 也可以使用字符串来生成“文本虚拟节点”。可选。
          [
            "先写一些文字",
            createElement("h1", "一则头条"),
            createElement(MyComponent, {
              props: {
                someProp: "foobar",
              },
            }),
          ]
        );

}

最终解决方案如下:

data(){
    const vm = this
    const columns = [
        {
          title: 'Home phone',
          colSpan: 2,
          dataIndex: 'tel',
          customRender: (value, row, index) => {
            var child = vm.$createElement('a',{
                domProps:{
                    innerHTML:value
                },
                on:{
                    click:function(){
                        vm.handleClick(value,row,index)
                    }
                }
            })
            const obj = {
              children: value,
              attrs: {},
            };
            if (index === 2) {
              obj.attrs.rowSpan = 2;
            }
            // These two are merged into above cell
            if (index === 3) {
              obj.attrs.rowSpan = 0;
            }
            if (index === 4) {
              obj.attrs.colSpan = 0;
            }
            return obj;
          },
        },
    ]
    return {
        columns,
    }
}
methods:{
    handleClick(value,row,index){
        //...
    }
}