<template>
<div id="chart" style="width: 100%; height: 400px;"></div>
</template>
<script>
export default {
mounted() {
this.renderChart()
},
methods: {
renderChart() {
const chart = this.$echarts.init(document.getElementById('chart'))
// 构建图表配置
const options = {
// 图表类型
chartType: 'bar',
// 图表数据
data: [
{ name: '小米', value: 400 },
{ name: '华为', value: 500 },
{ name: '联想', value: 300 },
{ name: '苹果', value: 700 },
{ name: '三星', value: 300 }
]
}
// 根据配置渲染图表
this.renderChartByType(chart, options)
},
renderChartByType(chart, options) {
// 根据类型选择不同的图表
switch (options.chartType) {
case 'bar':
this.renderBarChart(chart, options.data)
break
case 'pie':
this.renderPieChart(chart, options.data)
break
// ...
default:
break
}
},
renderBarChart(chart, data) {
const seriesData = data.map(item => item.value)
const xAxisData = data.map(item => item.name)
const options = {
// 图表类型
type: 'bar',
// X轴数据
xAxis: {
type: 'category',
data: xAxisData
},
// Y轴数据
yAxis: {
type: 'value'
},
// 数据系列
series: [
{
data: seriesData,
type: 'bar'
}
]
}
chart.setOption(options)
},
renderPieChart(chart, data) {
const seriesData = data.map(item => ({
name: item.name,
value: item.value
}))
const options = {
// 图表类型
type: 'pie',
// 图表标题
title: {
text: '饼图示例'
},
// 数据系列
series: [
{
type: 'pie',
data: seriesData
}
]
}
chart.setOption(options)
}
}
}
</script>