前言
今天在使用 tdesign 的 table 表格的时候,需要在表格后面自定义按钮
const columns = [
{ colKey: 'id', title: 'ID' },
{
colKey: 'pr_remark',
title: '说明',
width: 120,
},
{ colKey: 'pr_status', title: '状态' },
{
title: '操作栏',
colKey: 'operate',
width: 150,
cell: (h, { row })=><t-link theme="primary" hover="color" data-id={row.key} onClick={this.onEdit}>编辑</t-link>
}
]
按照官方上的写法是可以这样子自定义表格最后一格的内容的,但是在没有引入jsx语法的项目当中就会报错。
如果想要使用 lang="jsx" 的话,还需要引入插件来支持,所以今天对于这种简单的jsx需求,可以有另一种简单的方案
h函数
在vue3.0中,h函数就是vue中的createElement方法,这个函数的作用就是创建虚拟dom,追踪dom变化,可以实现展示template如何渲染到html中的过程。
我们一般在编写vue代码时,会首先编写模板代码,也就是template标签中的代码。如果我们想要比模板更加接近编译器,此时我们可以使用渲染函数。
我们编写的代码转化为真正的dom
时,首先会先转换为VNode
,然后多个Vnode
进行结合起来转化为VDOM
,最后VDOM
才渲染成真实的DOM
,此时我们思考一个问题,如果我们直接编写生成vnode
的代码,效率会更高,这里我们就是h
函数。h
函数我们也可以称为createVnode
函数。
所以在这里我们还可以用h函数来代替jsx语法,一样能够渲染出我们想要的节点,关于h函数的使用,移步 Vue官方文档
这样我们就可以成功生成自定义的表格项
const columns = ref([
{ colKey: 'id', title: 'ID' },
{
colKey: 'pr_remark',
title: '说明',
width: 120,
},
{ colKey: 'pr_status', title: '状态' },
{
colKey: 'operate',
title: '操作栏',
cell: () => {
return h('div',{id: 'foo', class: 'bar', onClick: ()=>increment()}, '编辑' // props[/* children */]
);
},
},
]);
并且成功响应绑定的点击事件,样式也可以通过类来进行修改,甚至添加多个按钮
const columns = ref([
{ colKey: 'id', title: 'ID' },
{
colKey: 'pr_remark',
title: '说明',
width: 120,
},
{ colKey: 'pr_status', title: '状态' },
{
colKey: 'operate',
title: '操作栏',
cell: (h, { row }) => {
console.log('@@@@',h,row);
return h('div',{class: 'operate'}, [
h('span',{class: 'edit', onClick: ()=>itemEdit(row)}, '编辑'),h('span',{class: 'delete', onClick: ()=>itemDelete(row.id)},'删除')
]);
},
},
]);