uniapp如何使用百度echarts图表

发布于:2022-10-17 15:49:33

uniapp如何使用百度echarts图表与高德地图。官方提供的方案是模式,该方式支持DOM操作。

注意:renderjs模式仅支持APP与H5,如要想兼容小程序,请到社区找插件实现小程序图表。

百度echarts图表使用方法步骤:

步骤一:到百度官网下载 echarts.min.js  【https://echarts.apache.org/zh/index.html

步骤二:将echarts.min.js放在【**项目/static/js/echarts.min.js】文件夹下

步骤三:封装一个Echarts.vue公共的组件,该组件在【**项目/components/Echarts/Echarts.vue】文件夹下。其代码如下

<template>
  <view>
    <!-- #ifdef APP-PLUS || H5 -->
    <view
          :id="echartsID"
          :change:id="ModuleInstance.reciveID"
          :option="option"
          :change:option="ModuleInstance.setOption"
          :style="{height:`${height}rpx`}"></view>
    <!-- #endif -->

    <!-- #ifndef APP-PLUS || H5 -->
    <view>非 APP、H5 环境不支持renderjs模式"</view>
    <!-- #endif -->
  </view>
</template>

<script>
export default {
  props: {
    height: {
      type: Number,
      default: 520,
      required: false,
    },
    option: {
      type: Object,
      default: () => {},
      required: false,
    },
  },
  data() {
    return {
      echartsID: `echartsID-${Date.now()}-${parseInt(Math.random() * 1e8)}`, //生成唯一的ID
    };
  },
  /*注意:uniapp子组件是没onLoad()和onShow()生命周期,只有页面组件才有 */
  mounted() {},
  methods: {},
};
</script>
<script module="ModuleInstance">
//let myChart;深坑:同一个页面同时引入该组件,myChart变量会被替换成最后一个实例,所以使用this.myChart保存实例
export default {
    data() {
        return {
            echartsID: '',//接收唯一的ID
            myChart:null,
        };
    },
    mounted(){
        if (typeof window.echarts === 'function') {
            // 观测更新的数据在 view 层可以直接访问到
            this.initEchart();
        } else {
            // 动态引入较大类库避免影响页面展示
            const script = document.createElement('script');
            // view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
            script.src = 'static/js/echarts.min.js';
            //script标签的onload事件都是在外部js文件被加载完成并执行完成后才被触发的
            script.onload = () => {
                this.initEchart();
            }
            document.head.appendChild(script); 
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.myChart.resize)
        this.myChart.dispose()
    },
    methods: {
        initEchart(){
            this.myChart = echarts.init(document.getElementById(this.echartsID));
            this.myChart.setOption(this.option || {});
            window.addEventListener('resize', this.myChart.resize);
        },
        reciveID(id) {
            this.echartsID = id;
        },
        setOption(newValue, oldValue, ownerInstance, instance){
            if(this.myChart){
                this.myChart.clear();//清空画布
                this.myChart.setOption(newValue || {});
            }
        }
    },
};
</script>
<style>
.component-baidu-echarts {
  .echarts {
    width: 100%;
    min-height: 50px;
  }
}
</style>

页面内的使用方式如下。注:如果页面中需要使用到echarts实例的方法,可以通过require()方法导入。

<template>
  <view class="component-echarts">
    <Echarts :option="echartOptions" :height="650" />
  </view>
</template>

<script>
import Echarts from "@/components/Echarts/Echarts";
let echarts = require("@/static/js/echarts.min.js");
export default {
  components: { Echarts },
  data() {
    return {
      echartOptions: {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
                {
                    data: [150, 230, 224, 218, 135, 147, 260],
                    type: 'line',
                    areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: "rgba(24, 144, 255, 0.3)",
                            },
                            {
                                offset: 1,
                                color: "rgba(255,255,255,0)",
                            },
                        ]),
                    },
                }
            ]
        },
    };
  },
  onShow() {},
  methods: {},
};
</script>

页面内的使用方式如下。注:如果页面中需要使用到echarts实例的方法,可以通过require()方法导入。

<template>
  <view class="component-echarts">
    <Echarts :option="echartOptions" :height="650" />
  </view>
</template>

<script>
import Echarts from "@/components/Echarts/Echarts";
let echarts = require("@/static/js/echarts.min.js");
export default {
  components: { Echarts },
  data() {
    return {
      echartOptions: {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
                {
                    data: [150, 230, 224, 218, 135, 147, 260],
                    type: 'line',
                    areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: "rgba(24, 144, 255, 0.3)",
                            },
                            {
                                offset: 1,
                                color: "rgba(255,255,255,0)",
                            },
                        ]),
                    },
                }
            ]
        },
    };
  },
  onShow() {},
  methods: {},
};
</script>

以下是对uniapp缺陷的补充:
注意:uniapp的APP端逻辑层与视图层的数据(对象数组)传输,应该是经过JSON.stringify格式化后传输的,所以会导致echarts的yAxis.axisLabel. formatter函数被清空。APP端逻辑层与视图层之间的js是完全独立的环境运行,不能像H5那样挂载全局变量解决传参(uni.XXX、Vue.prototype.XXX),所以要想解决上面的问题,只能是在renderjs内添加formatter函数。
解决方法:利用【_formatter】字段做判断,补上formatter函数

<script module="ModuleInstance">
export default {
    methods: {
        initEchart(){
            this.myChart = echarts.init(document.getElementById(this.echartsID));                    
            this.handleYAxisAxisLabelFormatter(this.option);
            this.myChart.setOption(this.option || {});
            window.addEventListener('resize', this.myChart.resize);
        },
        setOption(newValue, oldValue, ownerInstance, instance){
            if(this.myChart){
                this.myChart.clear();//清空画布
                this.handleYAxisAxisLabelFormatter(newValue);
                this.myChart.setOption(newValue || {});
            }
        },
        //Y轴,数字过大,缩减数字后,在其后面添加【万】【亿】
        handleYAxisAxisLabelFormatter(option){
            let handleYAxis = (obj)=>{
                if(obj.axisLabel && obj.axisLabel._formatter === true){
                    delete obj.axisLabel?._formatter;
                    obj.axisLabel.formatter = (value, index) => {
                        return this.axisLabelFormatter(
                            value,
                            index,
                            option.series
                        );
                    }
                }
            }
            if(Object.prototype.toString.call(option.yAxis) == '[object Array]'){
                for (let i = 0; i < option.yAxis.length; i++) {
                    handleYAxis(option.yAxis[i]);
                }
            }
            if(Object.prototype.toString.call(option.yAxis) == '[object Object]'){
                handleYAxis(option.yAxis);
            }
        },
        //返回的数后面带【万、亿】
        axisLabelFormatter(value, index, series) {
            let unit = "";
            let max = 0;
            series = series || [];
            for (let i = 0; i < series.length; i++) {
                let num = Math.max.apply(null, series[i].data);
                max = Math.max(num, max);
            }
            if (max > 1e4 && max <= 1e8) {
                unit = "万";
                value = Math.floor((value * 100) / 1e4) / 100; //保留两位小数,向下取整
            }
            if (max > 1e8) {
                unit = "亿";
                value = Math.floor((value * 100) / 1e8) / 100; //保留两位小数,向下取整
            }
            return value + unit;
        },
    },
};
</script>
<script>
export default {
  components: { Echarts },
  data() {
    return {
      echartOptions: {
        yAxis: [
          {
            type: "value",
            splitNumber: 5,
            axisLabel: {
              _formatter: true,//该字段是自定义的,仅用于判断
              //formatter: (value, index) => {},//uniapp的renderjs传参不支持函数
            },
          },
        ],
    };
  },
};
</script>





作者:随风飘_c165
链接:https://www.jianshu.com/p/409e5453fd38
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


阅读 181+

一片空白

父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。