vue项目里使用ECharts图表后台返回图表数据

最近项目里面要使用到图标,感觉ECharts挺不错,就添加到项目里了,图标数据是后台返回的.

1.vue引入echarts

npm install echarts -S (导入方法有很多,根据需要自行选择)

2.main.js全局引用

import ECharts from 'echarts'
Vue.prototype.echarts=ECharts;
Vue.use(ECharts);

3.在具体文件中使用

<template>
    <section class="section">
        <Breadcrumb>
            <BreadcrumbItem>首页</BreadcrumbItem>
        </Breadcrumb>
        <Divider/>
        <div id="main" style="width:600px;height:400px;">
        </div>
    </section>
</template>
<script>
    export default {
        data() {
            return {
             
            }
        },
        mounted() {
            this.charts();
        },
        methods: {
            charts(){
               let chart=this.echarts.init(document.getElementById('main'));
                //ajax请求接口获取数据
                this.Axios({
                    url: '你自己的后台接口地址',
                    params: _params,
                }).then(response => {
                    var res = response.data;
                    if (res && res.code === '0') {
                        chart.setOption(res);
                    } else {
                        this.$Message.error(res.msg);
                    }
                }, error => {
                    if (error.response) {
                        const _result = error.response.data;
                        this.$Message.error(_result.msg);
                    } else {
                        this.$Message.error('操作异常,请检查网络!');
                    }
                });
            } ,
        },
        components: {}
    }
</script>

4.后台代码

封装了一个EChartsOptionUtil工具类

package cn.rocketai.saas.common.util;

import com.github.abel533.echarts.axis.AxisTick;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.code.*;
import com.github.abel533.echarts.feature.DataView;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.feature.Mark;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.LineStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;

import java.util.HashMap;
import java.util.Map;

/** ECharts图表工具类 Author: dengWenBo Date: 19-1-16 */
public class EChartsOptionUtil {

  /**
   * 生成柱状图的Option
   *
   * @param xValue X轴的值
   * @param yValue Y轴的值
   * @param title 标题
   * @param legend 图例(单位)
   * @param xName
   * @param yName
   * @return
   */
  public static GsonOption getBarGraphOption(
      Object[] xValue, Object[] yValue, String title, String legend, String xName, String yName) {

    GsonOption option = new GsonOption();

    if (title != null) {
      option.title(title); // 标题
    }
    // 工具栏
    option
        .toolbox()
        .show(true)
        .feature(
            Tool.mark, // 辅助线
            new DataView().show(true).readOnly(true), // 数据视图 Tool.dataView
            new MagicType(Magic.line, Magic.bar), // 线图、柱状图切换
            Tool.restore, // 还原
            Tool.saveAsImage); // 保存为图片
    option
        .tooltip()
        .show(true)
        .trigger(Trigger.axis)
        .formatter("{a} <br/>{b} : {c}"); // 显示工具提示,设置提示格式

    if (legend != null) {
      option.legend(legend); // 图例
    }

    // x轴
    CategoryAxis xCategory = new CategoryAxis();
    // x轴数据配置 500 x宽度
    xCategory.data(xValue).boundaryGap(true).name(xName).nameGap(500).type();
    // 如果x轴数据过多者隔一个显示interval(1)隔一个显示rotate(30)倾斜度
    if (xValue.length > 10) {
      xCategory.axisLabel().position("end").interval(1).rotate(0);
    } else {
      xCategory.axisLabel().position("end").interval(0).rotate(0);
    }
    xCategory.splitLine().show(true).lineStyle(new LineStyle().type(LineType.dashed));
    xCategory.axisTick(new AxisTick().show(true).inside(true));
    option.xAxis(xCategory);

    // y轴
    // yAxis[{name : '区域销量',nameLocation : 'end',nameGap : 20,type : 'value'}],

    CategoryAxis yCategory = new CategoryAxis();
    yCategory.name(yName).type(AxisType.value).position("end");
    yCategory.splitLine().show(true).lineStyle(new LineStyle().type(LineType.dashed));
    option.yAxis(yCategory);
    // 图类别(柱状图)
    Bar bar = new Bar();
    // 循环数据
    for (int i = 0; i < xValue.length; i++) {
      // 类目对应的柱状图
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("value", yValue[i]);
      map.put("itemStyle", new ItemStyle().normal(new Normal().color("#01B9D4"))); // 图形颜色
      // map.put("barWidth", 20); // 柱状图的宽度 如果数据过少设置宽度为20
      // map.put("barMaxWidth", 20);
      bar.data(map);
    }
    bar.name(legend);
    if (xValue.length < 3) {
      // 设置柱状图 宽度
      bar.barWidth(100);
    }
    option.series(bar);
    return option;
  }
}

根据需求写实现类

public Option ageData(User currUser) {
    // 年龄段0-15,16-25,26-35,36-45,大于46
    List<String> ageFifteen = dataAnalysisMapper.selectByAge(currUser.getId(), "0~15岁");
    List<String> ageTwenty = dataAnalysisMapper.selectByAge(currUser.getId(), "16~25岁");
    List<String> ageThirty = dataAnalysisMapper.selectByAge(currUser.getId(), "26~35岁");
    List<String> ageForty = dataAnalysisMapper.selectByAge(currUser.getId(), "35~45岁");
    List<String> overFort = dataAnalysisMapper.selectByAge(currUser.getId(), "⼤于46岁");
    List<Object> x = new ArrayList<>();
    x.add("0~15岁");
    x.add("16~25岁");
    x.add("26~35岁");
    x.add("35~45岁");
    x.add("⼤于46岁");
    Object[] xObject = x.toArray(new Object[0]);
    List<Object> y = new ArrayList<>();
    y.add(String.valueOf(ageFifteen.size()));
    y.add(String.valueOf(ageTwenty.size()));
    y.add(String.valueOf(ageThirty.size()));
    y.add(String.valueOf(ageForty.size()));
    y.add(String.valueOf(overFort.size()));
    Object[] yObject = y.toArray(new Object[0]);
    return getOption(xObject, yObject, "年龄段", "年龄段");
  }

最后把数据返回前台(最后的数据需要toString() )

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要将后台数据插入到 Vue 3 ECharts 项目页面上,你可以按照以下步骤进行操作: 1. 在你的 Vue 3 项目中安装 ECharts 和 Axios(用于从后台获取数据): ``` npm install echarts axios ``` 2. 在你的 Vue 组件中引入 ECharts 和 Axios: ```javascript import * as echarts from 'echarts'; import axios from 'axios'; ``` 3. 创建一个用于渲染 ECharts 图表的容器,在你的模板中添加一个具有唯一标识符的元素: ```html <template> <div id="chart-container"></div> </template> ``` 4. 在你的 Vue 组件中获取后台数据,并将数据渲染到图表上: ```javascript import { ref, onMounted } from 'vue'; export default { setup() { const chartContainer = ref(null); onMounted(() => { axios.get('your-backend-api-url') .then(response => { const data = response.data; // 创建一个 ECharts 实例 const myChart = echarts.init(chartContainer.value); // 构造图表数据 const option = { // 配置图表选项,根据需要设置 x 轴、y 轴等 // ... series: [ { name: 'Series Name', type: 'bar', data: data, }, ], }; // 使用刚指定的配置项和数据显示图表 myChart.setOption(option); }) .catch(error => { console.error(error); }); }); return { chartContainer, }; }, }; ``` 在上述代码中,我们使用 `axios` 库从后台获取数据,并在 `onMounted` 钩子函数中进行图表的渲染。获取到数据后,我们创建一个 ECharts 实例,并根据需要配置图表选项和数据。最后,使用 `setOption` 方法将配置项和数据应用于图表。 请注意,上述代码仅提供了一个基本的示例,实际应用中可能还需要根据具体需求进行更多的配置和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值