当我们页面上,有好多相同的图表(echarts)或者表格(table)的时候,但是只是表里的数据显示的不同。这时候可以不用每个表都新建一个.vue文件,可以公用一个组件,动态传递不同的数据。下面就实现如何动态传递组件里的数据,从而减少文件新建的冗余。
先看图:
我们不需要创建5个相同的.vue组件文件,只需要创建一个就行。
首先创建index.vue文件,在创建组件worksShopTable.vue组件文件。
在index.vue里请求数据,并且返回给组件。(这里用虚拟数据,没有从接口请求)
data() {
return {
tableData: [
{
workshopName: '000',
datas: [
{
WEIGHT: 520,
CREATED: '2021-10-12 14:15:23',
EMES_FACILITIES_ID: '014',
ADDMAT_TYPE: '2'
},
{
WEIGHT: 300,
CREATED: '2021-10-12 13:45:45',
EMES_FACILITIES_ID: '153',
ADDMAT_TYPE: '2'
}
},
{
workshopName: '111',
datas: [
{
WEIGHT: 180,
CREATED: '2021-10-12 15:54:34',
EMES_FACILITIES_ID: '604',
ADDMAT_TYPE: '2',
RUN_NO: 'JS210860401',
Id: 0
}
]
}
在index里引入组件worksShopTable(如何引入组件请自行百度)。
之后用v-for循环data数据里的数据,注意要写key属性,否则会报错。并且在组件标签里绑定数据::tableData=“item",会把这个el-rol循环item次,生成对应个数的表table。
<el-row type="flex" justify="space-between" style="width:100%; height:100%; flex-wrap: wrap;">
<!-- 会循环item个列表 -->
<el-col v-for="(item, index) in tableData" :key="index" span="12">
<worksShopTable :tableData="item" />
</el-col>
</el-row>
在worksShopTable.vue组件中,用props定义数据:写在export default里面。
props: {
tableData: {
type: Object,
required: true
}
}
在el-table里绑定:data属性,:data=“tableData.datas”,用scope.row完成每行数据的循环显示在表格里。
<el-table
:row-style="{}"
:cell-style="{ color: '#fff', fontSize: '0.28rem' }"
:header-row-style="{}"
:data="tableData.datas"
:header-cell-style="{ fontSize: '0.3rem' }"
style="width: 90% ;left:0.5rem;top:1rem;position: absolute;"
height="65%"
>
<!-- -->
<el-table-column label="宽度">
<template slot-scope="scope">
{{ scope.row.WEIGHT }}
</template>
</el-table-column>
<el-table-column prop="stove" label="创建时间">
<template slot-scope="scope">
{{ scope.row.CREATED }}
</template>
</el-table-column>
<el-table-column prop="feed" label="设施id">
<template slot-scope="scope">
{{ scope.row.EMES_FACILITIES_ID }}
</template>
</el-table-column>
<el-table-column prop="size" label="类型">
<template slot-scope="scope">
{{ scope.row.ADDMAT_TYPE === 1 ? '首投' : '复投' }}
</template>
</el-table-column>
</el-table>
注意:
tableData的数据类型是Object还是Array自己根据实际需求定义。
props属性:父组件向子组件传递数据使用的
父子组件之间的通信就是 props down,events up,父组件通过 属性props向下传递数据给子组件,子组件通过 事件events 给父组件发送消息。