render 函数
跟 template
一样都是创建 html 模板的,但是有些场景中用 template
实现起来代码冗长繁琐而且有大量重复,这时候就可以用 render 函数
。
render方法必须返回一个createElement函数的调用结果,也就是模版内的顶层元素(这个方法在vue2的习惯性使用中经常用h来作为createElement的别名)。
应用场景举例说明:在Table组件中,根据当前单元格的不同字段在前面加上不同的圆点样式
对单元格的添加render函数:
{
title: '申请状态',
key: 'sheetStatusName',
width: 120,
align: 'center',
render: this.sheetStatusStyle
}
函数定义:
sheetStatusStyle(h, { row }) {
const dot = { background: null, height: '6px', width: '6px', borderRadius: '3px', marginRight: '10px', marginTop: '13px', display: 'inline-block' };
const th = this;
const jump = {
on: {
click() {
th.linkTo(row);
}
}
};
const name = '查看';
switch (row.sheetStatusName) {
case '待审核':
dot.background = '#00a0ff';
break;
case '已驳回':
dot.background = '#ED5354';
break;
case '已完成':
dot.background = '#00D166';
break;
default:
dot.background = '#F5A623';
}
return (
<div>
<span style={dot}></span>
<span>{row.sheetStatusName}</span>
<a {...jump}>{name}</a>
</div>
);
}