1. 首先最基本的,vue elementUI根据数据生成固定表项的表格
从官网摘个Demo过来:
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
// tableData: [
// {date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄'},
// {date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1517 弄'}]
样式如下:
2. 如果表项也动态生成呢?
// 实际返回的数据一般是:
testDatas: [
{'No': 1, 'name': '张三', 'age': 24, 'city': '广州', 'tel': '13312345678'},
// ...
]
// 获取数据后,转换下格式,用一个数组存‘项名’
testCols: ["No.","name","age","city","tel"],
testDatas: [
{col_0: 1, col_1: '张三', col_2: 24, col_3: '广州', col_4: '13312345678'},
{col_0: 2, col_1: '李四', col_2: 25, col_3: '九江', col_4: '18899998888'},
{col_0: 3, col_1: '王五', col_2: 26, col_3: '六盘水', col_4: '13600001111'},
{col_0: 4, col_1: '赵二', col_2: 27, col_3: '菏泽', col_4: '13145209420'},
]
模板绑定如下:
<el-table :data="testDatas" border stripe style="width: 100%">
<el-table-column v-for="(col, idx) in testCols" :prop="'col_'+idx" :label="col" :key="idx"></el-table-column>
</el-table>
显示:
3. 单元格可编辑
网上早有网友讨论过这个功能,我采用的是将单元格数据转换成对象,添加属性show来控制其在文字与输入框间切换。听起来就不想下手,又要转换数据格式了。。
// 表项(头)
testCols: [
{col: "name", txt: 'name', show: true},
{col: "age", txt: 'age', show: true},
{col: "city", txt: 'city', show: true},
{col: "tel", txt: 'tel', show: true}
],
// 数据
testDatas: [{
name: {content: '张三', show: true},
age: {content: 24, show: true},
city: {content: '广州', show: true},
tel: {content: '13312345678', show: true}
},{
name: {content: '李四', show: true},
age: {content: 25, show: true},
city: {content: '九江', show: true},
tel: {content: '18899998888', show: true}
}
]
<el-table :data="testDatas" border style="width: 100%">
<el-table-column v-if="testCols.length > 0" type="index" :label="'编号'" :width="50"></el-table-column>
<el-table-column v-for="(column, idx) in testCols" :key="idx">
<!-- 表头 -->
<template slot="header" slot-scope="scope1">
<p v-show="testCols[idx].show" @dblclick="testCols[idx].show=false">
{{column.txt}}
<i class="el-icon-edit-outline" @click="testCols[idx].show=false"></i>
</p>
<el-input
size="mini"
v-show="!testCols[idx].show"
v-model="testCols[idx].txt"
@blur="testCols[idx].show=true">
</el-input>
</template>
<!-- 内容绑定 -->
<template slot-scope="scope">
<!-- 双击文字或点击修改图标以更改"show"属性,显示input框 -->
<p v-show="scope.row[column.col].show" @dblclick="scope.row[column.col].show=false">
{{scope.row[column.col].content}}
<i class="el-icon-edit-outline" @click="scope.row[column.col].show=false"></i>
</p>
<!-- 失去焦点时更改"show"属性,显示文本 -->
<el-input type="textarea" :autosize="{minRows:2,maxRows:4}"
v-show="!scope.row[column.col].show"
v-model="scope.row[column.col].content"
@blur="scope.row[column.col].show=true">
</el-input>
</template>
</el-table-column>
</el-table>

4. 插入、删除一行或一列数据
暂缺,有空再补上
来源:CSDN
作者:ymzhaobth
链接:https://blog.csdn.net/ymzhaobth/article/details/104716431