最近在使用iView中的表格组件时,碰到许多坑和疑惑,仔细研究了一下table组件,发现官方文档讲的不是很清楚,本文将介绍并使用table组件,作一个动态建立表格的demo,效果以下图。欢迎到个人博客访问。react
查看官方文档可知,表格中主要的两个属性分别为columns
和data
。columns
用来渲染列,data
是渲染所用的数据,想在iView中插入标签,须要用它提供的render
函数,这跟react的render差很少。数组
render函数的几个参数:bash
h
: Render
函数的别名(全名 createElement
)iview
params
: table
该行内容的对象,包含row
(当前行对象)和index
(当前行的序列号)函数
props
:设置建立的标签对象的属性ui
style
:设置建立的标签对象的样式this
on
:为建立的标签绑定事件spa
render: (h, { row, index }) => {
return h("Input", {
props: {
value: row.name
},
on: {
input: val => {
this.data[index].name = val;
}
}
});
}
复制代码
这是一个插入Input框的例子。code
h
渲染出<input>
标签prop
设置其value
为当前行的name
on
添加input
方法,使当前行的name
为输入的值{
title: "爱好",
key: "hobby",
render: (h, { row, index }) => {
return h("Select", {
props: {
value: row.hobby
},
on: {
'on-select': val => {
this.data[index].hobby = val;
}
}
},
this.options.map(item=>{
return h('Option',{
props:{
value:item,
label:item
}
})
})
);
}
},
复制代码
这是一个插入Select框的例子cdn
将要嵌套的组件用花括号放在后面,option
可经过map
函数就能够代替v-for
的渲染。
若是要嵌套多个组件,能够写成数组的形式。好比:
render: (h, params) => {
return h('div', [
h('Button'),
h('Button')
]);
}
复制代码
插入Select
组件的时候,若是table行数较少,会出现遮住下拉框的状况。
overflow: visible
。 Select
组件的触发事件为on-change
须要用props
设置初始值,不然值不会渲染到真正的当前行。
<template>
<div class="table">
<Button class="button" @click="add">Add</Button>
<Table :columns="columns" :data="data" class="table-fixbug"></Table>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
columns: [
{
type: "selection",
width: 60,
align: "center"
},
{
title: "姓名",
key: "name",
render: (h, { row, index }) => {
return h("Input", {
props: {
value: row.name
},
on: {
input: val => {
this.data[index].name = val;
}
}
});
}
},
{
title: "爱好",
key: "hobby",
render: (h, { row, index }) => {
return h("Select", {
props: {
value: row.hobby
},
on: {
'on-select': val => {
this.data[index].hobby = val;
}
}
},
this.options.map(item=>{
return h('Option',{
props:{
value:item,
label:item
}
})
})
);
}
},
{
title: "职业",
key: "job",
render: (h, { row, index }) => {
return h("Input", {
props: {
value: row.job
},
on: {
input: val => {
this.data[index].job = val;
}
}
});
}
},
{
title: "operation",
key: "operation",
render: (h, { row, index }) => {
return h(
"a",
{
on: {
click: () => {
this.data.splice(index, 1);
}
}
},
"Delete"
);
}
}
],
data: [
{
name: "",
hobby: "",
job: ""
}
],
options:['电影','游戏','看书']
};
},
methods: {
add() {
const addData = {
name: "",
hobby: "",
job: ""
};
this.data.push(addData);
}
}
};
</script>
<style>
.table {
text-align: left;
}
.button {
margin-bottom: 20px;
}
.table-fixbug{
overflow: visible;
}
</style>
复制代码