1. vue引入echart
(1)首先安装ECharts库。可以通过npm
npm install echarts --save
(2)在vue页面中添加一个容器元素来显示图表
<el-card class="mt20"><div id="ha" ref="main"></div>
</el-card>
(3)在vue页面中的script引入echart,使用import * as echarts from 'echarts'
并且连接后端数据
<script>
import * as echarts from 'echarts'
import { getlineChartData} from "@/api/echartdata";
export default {name: "Index",data() {return {};},mounted() {//加载后初始化图表this.initEcarts();},methods: {initEcarts() {// 初始化echarts实例let myChart = echarts.init(this.$refs.main);getlineChartData().then(res => {console.log(res);console.log(res.axisData);console.log(res.seriesData1);console.log(res.seriesData2);let option = {title: {text: '每天数据'},//鼠标悬浮显示数字tooltip: {trigger: 'axis',axisPointer: {type: 'cross',label: {backgroundColor: '#6a7985'}}},legend: {data: ['联盟广告1', '联盟广告2']},xAxis: [{type: 'category',data: res.axisData,}],yAxis: [{type: 'value'}],series: [{name: '联盟广告1',type: 'line',data: res.seriesData1,},{name: '联盟广告2',type: 'line',data: res.seriesData2,}]};if (option && myChart.setOption) {// 使用刚指定的配置项和数据显示图表。myChart.setOption(option);}});}}
};
</script>
(5)样式
<style scoped lang="scss">
#ha {width: 80%;height: 360px;}
</style>
2. 后端Controller模拟接口
@GetMapping("/lineChartData")
public Map<String, Object> getLineChartData() {Map<String, Object> model = new LinkedHashMap<>();
model.put("axisData", new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"});
model.put("seriesData1", new Integer[]{120, 132, 101, 134, 190, 130, 120});
model.put("seriesData2", new Integer[]{220, 232, 101, 234, 290, 330, 220});
return model;
}
3. 后端查询数据
定义 :
public class EchartCount {public String name;public String count;
}
controller内容如下:
@GetMapping("/lineChartData")public Map<String, Object> getLineChartData() {List<EchartCount> saimaCountList=tEchartServcie.getLiXiangData();Map<String, Object> model = new LinkedHashMap<>();model.put("axisData", saimaCountList.stream().map(EchartCount::getName).collect(Collectors.toList()));model.put("seriesData1", saimaCountList.stream().map(EchartCount::getCount).collect(Collectors.toList()));model.put("seriesData2", return model;}