最近在使用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>
複製代碼