草庐IT

uniapp如何使用百度echarts图表

随风飘_c165 2023-03-28 原文

uniapp如何使用百度echarts图表与高德地图。官方提供的方案是 lang="renderjs"模式,该方式支持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 class="component-baidu-echarts">
    <!-- #ifdef APP-PLUS || H5 -->
    <view class="echarts"
          :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" lang="renderjs">
//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 lang="scss">
.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>

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

<script module="ModuleInstance" lang="renderjs">
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>

下面是uniapp项目封装的组件代码(推荐使用),利用对象深拷贝与toString()方法将函数转化成字符串,再用eval()函数将字符串解析出函数,这样就能解决uniapp函数被清空的问题,但是仅支持纯函数。注:如果该函数与它之前的作用域关系,那么这个函数执行将会异常。

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

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

<script>
import Vue from "vue";
export default {
  props: {
    height: {
      type: Number,
      default: 520,
      required: false,
    },
    option: {
      type: Object,
      default: () => {},
      required: false,
    },
 },
  watch: {
        option:{
            deep:true,//true为进行深度监听,false为不进行深度监听
            handler(newVal){
                this.deepCopy(newVal);
            }
        }
    },
  data() {
    return {
      echartsID: `echartsID-${Date.now()}-${parseInt(Math.random() * 1e8)}`, //生成唯一的ID
      optionDeepCopy:'',
    };
  },
  /*注意:uniapp子组件是没onLoad()和onShow()生命周期,只有页面组件才有 */
  mounted() {
        
  },
    methods: {
    //深拷贝
    deepCopy(option) {
        let recursion = (option, resultObj = {}) => {
            //递归函数
            for (const key in option) {
                if (Object.hasOwnProperty.call(option, key)) {
                    const element = option[key];
                    if (typeof element === 'object') {
                        resultObj[key] = (Object.prototype.toString.call(element) === '[object Array]') ? [] : {};
                        recursion(element,resultObj[key]);//递归
                    } else {
                        if (Object.prototype.toString.call(element) === '[object Function]') {
                            resultObj[key] = `${element.toString()}`;//将函数转成字符串
                        } else {
                            resultObj[key] = element;
                        }
                    }
                }
            }
            return resultObj;
        }
        let obj = recursion(option, {});
        // #ifdef APP-PLUS
        this.optionDeepCopy = JSON.stringify(obj);
        //#endif
        // #ifdef H5
        this.optionDeepCopy = this.option
        // #endif
    }
  },
};
</script>
<script module="ModuleInstance" lang="renderjs">
//let myChart;深坑:同一个页面同时引入该组件,myChart变量会被替换成最后一个实例
import Vue from "vue";
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));
            if(this.option)this.handleYAxisAxisLabelFormatter(this.option);
            this.myChart.setOption(this.option || {});
            this.checkEmptyData();
            window.addEventListener('resize', this.myChart.resize);
        },
        reciveID(id) {
            this.echartsID = id;
        },
        setOption(newValue = '', oldValue, ownerInstance, instance){
            if(!newValue)return;
            newValue = this.handleStringToFunction(newValue);
            if(this.myChart){
                this.myChart.clear();//清空画布
                this.handleYAxisAxisLabelFormatter(newValue);
                this.myChart.setOption(newValue || {});
                this.checkEmptyData();
            }
        },
        //将字符串函数,转成可调用的函数
        handleStringToFunction(option) {
            if(Object.prototype.toString.call(option) === '[object String]'){
                option = eval("("+option+")");//将字符串转成对象
            }
            //递归
            let recursion = (option)=>{
                for (const key in option) {
                    //遍历:对象/数组
                    if (Object.hasOwnProperty.call(option, key)) {
                        const element = option[key];
                        if (Object.prototype.toString.call(element) === '[object String]' && (element.includes('function') || element.includes('=>'))) {
                            try {
                                option[key] = eval("("+element+")");//将字符串转成函数
                            } catch (error) {
                                uni.showToast({
                                    title: 'eval函数转换异常!',
                                    duration: 2000,
                                    icon: 'none'
                                });
                            }
                        }
                        if (Object.prototype.toString.call(element) === '[object Object]' || Object.prototype.toString.call(element) === '[object Array]') {
                            recursion(element);//递归
                        }
                    }
                }
            }
            recursion(option);
            return option;
        },
        //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;
        },
        //对空数据提示
        checkEmptyData(){
            if(!this.option)return;
            let {series = []} = this.option;
            if(series.length === 0){
                this.myChart.showLoading({
                    text: '暂无数据',
                    showSpinner: false,    // 隐藏加载中的转圈动图
                    textColor: '#aaa',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    fontSize: '14px',
                    fontWeight: 'normal',//bold
                    fontFamily: 'Microsoft YaHei'
                });
            }else{
                this.myChart.hideLoading();
            }
        }
    },
};
</script>
<style lang="scss">
.component-baidu-echarts {
  .echarts {
    width: 100%;
    min-height: 50px;
  }
}
</style>

高德地图的js只能使用在线链接,需要申请【key与安全密钥】。高德地图如果点击事件交互频繁,建议直接在 renderjs模式中实现功能。

更多百度图表示例:http://www.isqqw.com/

uniapp高德地图使用:
https://www.jianshu.com/p/57ebc0eef122

uniapp中的renderjs模式数据通信方式,请参考如下博客:

http://events.jianshu.io/p/8cd2b0db7b65

https://m.php.cn/uni-app/481299.html

有关uniapp如何使用百度echarts图表的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐