编写Vue工程代码,根据接口,用柱状图展示接口所有数据中各设备各个状态持续时长(秒)
时间: 2024-02-24 14:57:14 浏览: 78
以下是一个简单的Vue组件,它可以根据接口数据展示柱状图。假设接口返回的数据格式如下:
```json
{
"data": [
{
"device": "设备1",
"status": "状态1",
"duration": 10
},
{
"device": "设备1",
"status": "状态2",
"duration": 20
},
{
"device": "设备2",
"status": "状态1",
"duration": 30
},
{
"device": "设备2",
"status": "状态2",
"duration": 40
}
]
}
```
```vue
<template>
<div>
<h2>设备状态持续时长</h2>
<div ref="chart" style="width: 100%; height: 500px;"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data() {
return {
chartData: null
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
// 调用接口获取数据
// 假设接口地址为 /api/status-duration
fetch('/api/status-duration')
.then(response => response.json())
.then(data => {
this.chartData = data
this.renderChart()
})
.catch(error => {
console.error(error)
})
},
renderChart() {
const chart = echarts.init(this.$refs.chart)
const devices = []
const statuses = []
const durations = []
// 处理数据
for (const item of this.chartData.data) {
if (!devices.includes(item.device)) {
devices.push(item.device)
}
if (!statuses.includes(item.status)) {
statuses.push(item.status)
}
}
for (let i = 0; i < devices.length; i++) {
const durationsRow = []
for (let j = 0; j < statuses.length; j++) {
const item = this.chartData.data.find(
x => x.device === devices[i] && x.status === statuses[j]
)
durationsRow.push(item ? item.duration : 0)
}
durations.push(durationsRow)
}
// 绘制图表
chart.setOption({
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: statuses
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: devices
},
yAxis: {
type: 'value'
},
series: statuses.map((status, index) => ({
name: status,
type: 'bar',
stack: '持续时长',
data: durations.map(row => row[index])
}))
})
}
}
}
</script>
<style>
/* 样式可以根据需要自行修改 */
</style>
```
这个组件通过调用接口获取数据,并使用 ECharts 绘制柱状图。在处理数据时,它会动态生成设备和状态的列表,并将持续时长转换为二维数组。最后,它使用 ECharts 的 setOption 方法绘制图表。
阅读全文