您的位置:首页 > Web前端 > Vue.js

vue element-ui table组件动态生成表头和数据并修改单元格格式 父子组件通信

2019-08-15 13:58 2687 查看

父组件

定义表头和表内容

data(){
return{
// 表格数据
tableColumns: [],
// 表头数据
titleData:[],
}
}

引入并注册子组件

import TableComponents from "../../components/table/table";
//注册子组件table
components: {
tableC: TableComponents
},

获取表头和表内容数据。(真实数据应该是从接口获取的,由于是测试数据这里我先写死)

mounted() {
this.titleData =
[{
name:'日期',
value:'date'
},{
name:'姓名',
value:'name'
},{
name:'地址',
value:'address'
},{
name:'汇率',
value:'sharesReturn'
}];
this.tableColumns =
[{
date: '2016-05-01',
name: '王小虎1',
address: '上海市普陀区金沙江路 1518 弄',
sharesReturn: 0.03
}, {
date: '2016-05-02',
name: '王小虎2',
address: '上海市普陀区金沙江路 1517 弄',
sharesReturn: 0.04
}, {
date: '2016-05-03',
name: '王小虎3',
address: '上海市普陀区金沙江路 1519 弄',
sharesReturn: -0.01
}, {
date: '2016-05-04',
name: '王小虎4',
address: '上海市普陀区金沙江路 1516 弄',
sharesReturn: 0.00
}];
}

html代码

<tableC :tableColumns="tableColumns" :titleData="titleData" ></tableC>

子组件

js代码

export default {
name: 'tbComponents',
props: ['tableColumns','titleData'],
}

重点来了

html要怎么写呢?官网的文档是这么写的

el-table :data关联的是表格里的数据

el-table-column :prop关联的是表头的值 :label关联的是表头的文本

html动态渲染

<el-table :data="tableColumns" style="width: 100%">
<el-table-column v-for="(item,key) in titleData" :key="key" :prop="item.value"
:label="item.name"></el-table-column>
</el-table>

效果如下:

最后剩下一个功能,如果 汇率大于0,则显示红色,小于0则显示绿色

先贴上完整代码:

<el-table :data="tableColumns" style="width: 100%">
<el-table-column v-for="(item,key) in titleData" :key="key" :prop="item.value" :label="item.name">
<template slot-scope="scope">
<span v-if="scope.column.property==='sharesReturn'&&scope.row[scope.column.property]>0" style="color:red">{{scope.row[scope.column.property]}}</span>
<span v-else-if="scope.column.property==='sharesReturn'&&scope.row[scope.column.property]<0" style="color: #37B328">{{scope.row[scope.column.property]}}</span>
<span v-else>{{scope.row[scope.column.property]}}</span>
</template>
</el-table-column>
</el-table>

scope.row和scope.column分别代表什么呢? 可以在界面输出看看

先输出scope.row

由此可见scope.row代表 当前行 的数据

再来输出scope.column

得到这样一个对象,仔细看看,我们可以发现一点门路

由此可见scope.column.property代表 当前列的值

合并起来,当前单元格的值应该是scope.row[scope.column.property]

总结

以上所述是小编给大家介绍的vue element-ui table组件动态生成表头和数据并修改单元格格式 父子组件通信,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐