首先要在Vue项目中安装echarts和axios:Copy
npm install echarts axios --save
在Vue组件中引入Echarts和axios并初始化图表:xmlCopy
<template>
<div id="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import echarts from 'echarts'
import axios from 'axios'
export default {
data() {
return {
chartData: []
}
},
mounted() {
this.getData()
},
methods: {
getData() {
axios.get('/api/chart-data')
.then(response => {
this.chartData = response.data
this.drawChart()
})
.catch(error => {
console.log(error)
})
},
drawChart() {
var myChart = echarts.init(document.getElementById('chart'))
myChart.setOption({
title: { text: 'ECharts 示例' },
tooltip: {},
xAxis: {
data: this.chartData.map(item => item.name)
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: this.chartData.map(item => item.value)
}]
})
}
}
}
</script>