Element-UI 可編輯表格 + 動态表頭
利用
el-table-column
的自定義列模闆可以與其他元件使用實作複雜的表格。
由于我想實作一個可編輯的表格,同時因為表格有很多個,同時列名也是不一樣的(數量和名稱),是以想偷個賴寫個動态的切換的功能。

以下為代碼:
<template>
<div>
<el-button @click="change">測試按鈕</el-button>
<el-table
:data="tableData"
class="tb-edit"
style="width: 100%">
<el-table-column v-for="item in tableHead":label="item.label" :property="item.property"
width="180">
<template slot-scope="scope">
<el-input v-model="scope.row[scope.column.property]" ></el-input>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">編輯</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import {example1, example2} from './columns';
export default {
name:'ruleTable',
data() {
return {
// 表頭
tableHead:example1,
// 資料值
tableData: [{
date: '2016-05-02',
name: '王小虎6666',
address: '上海市普陀區金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎45',
address: '上海市普陀區金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '王小虎333',
address: '上海市普陀區金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '王小虎222',
address: '上海市普陀區金沙江路 1516 弄'
}],
}
},
methods: {
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
},
change(){
this.tableHead = example2;
}
}
}
</script>
代碼關鍵在這裡:
<el-table-column v-for="item in tableHead":label="item.label" :property="item.property"
width="180">
<template slot-scope="scope">
<el-input v-model="scope.row[scope.column.property]" ></el-input>
</template>
</el-table-column>
通過一個循環拿到列的标簽和列名,格式如下:
// 表頭1
let example1=[
{
label:'姓名',
property:'name'
},{
label:'位址',
property:'address'
}
];
// 表頭2
let example2=[
{
label:'姓名',
property:'name'
},{
label:'位址',
property:'address'
},{
label:'日期',
property:'date'
}
];
export {
example1,
example2
};
在自定義模闆裡面通過
scope.row[scope.column.property]
取到目前行的列字段與輸入框進行雙向綁定,于是就是實作了可編輯的動态表頭的表格。
當然我們的表格資料也就可以根據實作來變化了。
vue-element-extends 這個基于 el-table 的封裝的可編輯表格不錯,推薦一波。@q平面人