开始
今天学习了一下前端的内容, 在做一个页面时用到了 iView 的 Table 组件, 其中需要自定义渲染列, 在此小记一下.
介绍
render 函数是为了在 Table 中自定义渲染列数据, 下面用例子进行说明.
如上图所示, 我想使用 render 函数在最后一列的操作列加上三个图标按钮, 代码应该这么写:
{
title: '操作', key: 'action',
render: (h, params) => {
return h('div', {}, [
// 编辑
h('Icon', {
props: {
type: 'ios-create',
color: '#2d8cf0',
size: '18',
},
style: {
cursor: 'pointer',
margin: '4px'
}
}),
// 删除
h('Icon', {
props: {
type: 'ios-trash',
color: '#ed4014',
size: '18',
},
style: {
cursor: 'pointer',
margin: '4px'
}
}),
// 设置
h('Icon', {
props: {
type: 'ios-settings',
color: '#2d8cf0',
size: '18',
},
style: {
cursor: 'pointer',
margin: '4px'
}
})
]);
}
}
另外一个要实现的功能是点击标题跳转到浏览器的新标签页, 也就是说将标题这一列渲染为 a 标签:
{
title: '标题', key: 'title',
render: (h, params) => {
return h('a', {
attrs: {
target: '_blank',
href: 'https://www.baidu.com/'
}
}, params.row.title);
}
}
我自己的理解
render 函数中的 h 参数是一个函数, 它有三个参数:
1. 渲染后的元素名称
比如标题我想将它渲染为一个 a 标签, 那么第一个参数就是 a(String 类型).
2. 渲染后的元素的属性
其中属性又分为标签本身的属性, iView 封装的属性; 还有就是 style 样式也可以写在这里面.
- 标签自己本身的属性, 比如 a 标签的 target 和 href 属性, img 的 src 属性.
- iView 封装的属性, 需要看 iView 具体的组件, 比如: Input 组件的 type 属性等等.
- style 样式, 不需要多说, 属性名全部是驼峰式写法.
我只截取 render 函数作说明:
// 1.
render: (h, params) => {
return h('a', {
// attrs 是标签自己本身的属性
attrs: {
target: '_blank',
href: 'https://www.baidu.com/'
}
}, '元素内容');
// 2.
render: (h, params) => {
return h('Input', {
// props 中是 iView 的属性
props: {
type: 'primary'
}
}, '元素内容');
}
// 3.
render: (h, params) => {
return h('a', {
attrs: {
target: '_blank',
href: 'https://www.baidu.com/'
},
// style 中是自定义的 css 样式
style: {
color: 'white',
// 这里需要是驼峰式写法
marginLeft: '5px'
}
}, '元素内容');
3. 元素中的内容
当然可以是文本, 也可以是HTML(HTML依然可以嵌套一个或者多个 h 函数).
render: (h, params) => {
let els = [
h('Button', {
// 样式省略 ...
}, '编辑'),
h('Button', {
// 样式省略 ...
}, '删除'),
];
return h('div', {
// 样式省略 ...
}, els);
上面我为了看的更清楚, 将子元素单独提出来作为 els 变量.