我们在vue开发中会遇到各种不同的需求,下面分享一个element ui动态表格的实现源码;
在template中的用到了element ui的表格el-table与v-for的一个渲染所实现:
<template>
<div>
<el-container>
<el-main>
<div>
<el-table border :data="tableData" style="width: 100%">
<!-- 序号 -->
<el-table-column
prop="date"
align="center"
label="序号"
:resizable="false"
type="index"
width="50"
>
</el-table-column>
<!-- // 动态循环表头数据 -->
<el-table-column
:label="item.val"
v-for="(item, index) in tableHead"
:key="index"
align="center"
>
<template scope="scope">
<span>{{ scope.row[item.item] }}</span>
</template>
</el-table-column>
<!-- 操作 -->
<el-table-column
fixed="right"
label="操作"
width="160"
align="center"
>
<template slot-scope="scope">
<el-button
@click="handleClick(scope)"
type="primary"
size="small"
>查看</el-button
>
<el-button type="primary" size="small">编辑</el-button>
</template>
</el-table-column>
</el-table>
</div>
</el-main>
</el-container>
</div>
</template>
数据是分为两个的:第一个是表头的数据,第二个是表格的数据
<script>
export default {
data() {
return {
// 表头数据
tableHead: [
{ val: "指标11111", item: "target1" },
{ val: "指标2", item: "target2" },
{ val: "指标3", item: "target3" },
{ val: "指标4", item: "target4" },
{ val: "指标5", item: "target5" },
],
// 表格数据
tableData: [
{
item: "项目1",
target1: 1111111111111111,
target2: 2,
target3: 3,
target4: 4,
target5: 5,
},
{
item: "项目2",
target1: 2111110,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
},
],
};
},
methods: {
handleClick(scope){
console.log(scope.row);
}
},
};
</script>
样式就没什么了:因为el-table自身在我们下载element ui时候就已携带;
<style lang="scss">
* {
margin: 0;
padding: 0;
}
</style>
效果图: