用e-charts画element ui表格后两列的相关曲线,要求点击不同的按钮能选择不同的两列,
时间: 2023-07-14 18:12:08 浏览: 58
可以通过以下步骤实现:
1. 首先,需要将表格数据转化为 e-charts 需要的格式。可以使用 `map` 方法将表格数据中需要的两列提取出来,然后分别存储到两个数组中。
2. 创建一个 e-charts 图表实例,并设置好图表的基本属性,例如图表的标题、x 轴和 y 轴的数据等。
3. 创建两个 `series` 对象,分别对应需要绘制的两个曲线。在 `series` 对象中,需要设置 `data` 属性为对应的数据数组,并设置 `type` 属性为 `'line'` 表示绘制折线图。
4. 创建一个按钮组件,用于选择需要绘制的两列数据。可以使用 `v-for` 指令遍历表格的表头,生成对应的按钮。每个按钮绑定一个点击事件,当点击按钮时,更新当前绘制的两列数据,并重新绘制图表。
5. 将图表实例挂载到页面上的容器中,完成图表的绘制。
以下是一个示例代码:
```html
<template>
<div>
<el-table :data="tableData" style="width: 100%">
<el-table-column v-for="(item, index) in tableHeader" :key="index" :label="item.label" :prop="item.prop"></el-table-column>
</el-table>
<div class="chart-container" ref="chart"></div>
<div class="btn-group">
<el-button v-for="(item, index) in tableHeader" :key="index" @click="handleBtnClick(index)">{{ item.label }}</el-button>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data() {
return {
tableHeader: [
{ label: '日期', prop: 'date' },
{ label: '销售量', prop: 'sales' },
{ label: '利润', prop: 'profit' }
],
tableData: [
{ date: '2021-01-01', sales: 100, profit: 50 },
{ date: '2021-01-02', sales: 200, profit: 80 },
{ date: '2021-01-03', sales: 150, profit: 60 },
{ date: '2021-01-04', sales: 300, profit: 120 },
{ date: '2021-01-05', sales: 250, profit: 100 }
],
chartData1: [], // 存储绘制曲线1的数据
chartData2: [] // 存储绘制曲线2的数据
}
},
mounted() {
this.initChart()
},
methods: {
initChart() {
// 创建图表实例
const chart = echarts.init(this.$refs.chart)
// 设置图表基本属性
chart.setOption({
title: {
text: '销售量和利润的关系'
},
tooltip: {},
legend: {
data: ['销售量', '利润']
},
xAxis: {
data: this.tableData.map(item => item.date)
},
yAxis: {},
series: [
{
name: '销售量',
type: 'line',
data: this.chartData1
},
{
name: '利润',
type: 'line',
data: this.chartData2
}
]
})
},
handleBtnClick(index) {
// 根据选择的按钮更新绘制曲线的数据
if (index === 1) {
this.chartData1 = this.tableData.map(item => item.sales)
this.chartData2 = this.tableData.map(item => item.profit)
} else if (index === 2) {
this.chartData1 = this.tableData.map(item => item.profit)
this.chartData2 = this.tableData.map(item => item.sales)
}
// 重新绘制图表
this.initChart()
}
}
}
</script>
<style>
.chart-container {
height: 400px;
}
.btn-group {
margin-top: 20px;
}
</style>
```
在上述示例中,我们首先将表格数据转化为了 e-charts 需要的格式,然后创建了一个图表实例,并绑定到页面上的容器中。接着,我们根据需要绘制的两列数据创建了两个 `series` 对象,并将其添加到图表实例中。最后,我们创建了一个按钮组件,用于选择需要绘制的两列数据。当点击按钮时,我们根据选择的列更新绘制曲线的数据,并重新绘制图表。