WeChat applet + ECharts to achieve dynamic refresh process record

WeChat applet + ECharts to achieve dynamic refresh process record

Preface

Recently I encountered a requirement, which is to refresh the chart in real time in a small program. At first I chose wx-chart, but then I found that it could not meet my needs. Finally I chose ECharts, but I also stepped on some pitfalls. By collecting information on the Internet, I finally figured it out and recorded my implementation process.

Method Examples

1. First, go to the ECharts official website to download its example, then copy the ec-canvas file and put it into your own project:

2. Then import the page you need and add it to xxx.json. Pay attention to the path here. My pages are all placed in the pages folder:

"usingComponents": {
    "ec-canvas": "../../ec-canvas/ec-canvas"
 }

3. Ok, let's get down to business. I'll give you an example of a page with two charts. Let's first get the simple layout and style right.

xxx.wxml:

Two canvas boxes need to be provided:

<view class="content">
    <ec-canvas id="mychart-one" canvas-id="mychart-multi-one" ec="{{ ecOne}}"></ec-canvas>
    <ec-canvas id="mychart-two" canvas-id="mychart-multi-two" ec="{{ ecTwo }}"></ec-canvas>
</view>

xxx.wxss:

.content {
    width: 100%;
    background-color: #F2F2F2;
    overflow-y: auto;
}
#mychart-one {
    position: absolute; 
    top: 0;
    height: 50%;
    left: 0;
    right: 0;
}
#mychart-two {
    position: absolute; 
    top: 50%;
    height: 50%;
    left: 0;
    right: 0;
}

It is worth noting here that if you want to put three charts, four charts or more, you must set the height of the canvas box, otherwise you will find that the last two charts are gone! ! Many official charts did not have a set height, so I put a few pictures according to the official ones, but found that none of them had the same effect. I was tired and searched for a long time before I realized that it was a style issue. I simply set a 50% height for each box.

4. Okay, now that all the preparations are done, the next step is the main part. (Actually, I think what I wrote is too complicated, full of repetitive code, but I don’t have time to integrate it for now. Friends who are interested can write their own methods to integrate it.)

xx.js

The first thing to do is to introduce the official component at the beginning of the page.

import * as echarts from '../../ec-canvas/echarts';

First set the style configuration to be displayed in the table

function setOption(chart, xdata, ydata) {
    const option = {
        title:
            text: 'Test',
            padding: [10, 0, 0, 20],
            textStyle: {
                fontSize: 14,
                color: '#696969'
            },
            top: '10rpx'
        },
        backgroundColor: "#fff",
        color: ["#006EFF", "#67E0E3", "#9FE6B8"],
        animation: false,
        grid: {
            show:false
        },
        xAxis:
            type: 'category',
            data: xdata, //The data on the x-axis is dynamic, so I pass it in as a parameter axisLabel: {
                interval: 5, //x-axis interval display scale formatter: function (value) { //display time var date = new Date(value * 1000);
                    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
                    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                    return h + m
                },
                fontSize: 8
            }
        },
        yAxis: {
            x: 'center',
            scale: true,
            type: 'value',
            axisLabel: {
                formatter: function (value) {
                var val = value / 1000000000 + 'G';
                    return val
                }
            }
        },
        series: [{
            type: 'line',
            data: ydata, //The data on the y-axis is also dynamic and is passed in as a parameter symbol: 'none',
            lineStyle:
                width: 1
            }
        }]
    };
    chart.setOption(option)
}

Some methods of writing pages

Page({
    data: {
        ecOne: {
            lazyLoad: true
        },
        ecTwo: {
            lazyLoad: true
        },
        timer:'' //Because I want to refresh in real time, I set a timer},
    onLoad: function (options) {
        var _this = this;
        this.getOneOption();
        this.getTwoOption();
        this.setData({ //Refresh every minute timer: setInterval(function () {
                    _this.getOneOption();
                    _this.getTwoOption();
                }, 60000)
        })
    },
    onReady: function () { //This step must be paid attention to this.oneComponent = this.selectComponent('#mychart-one');  
        this.twoComponent = this.selectComponent('#mychart-two');
    },
    onUnload: function () {
        clearInterval(this.data.timer)
    },
    init_one: function (xdata, ydata) { // Initialize the first chart this.oneComponent.init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            setOption(chart, xdata, ydata)
            this.chart = chart;
            return chart;
        });
    },
    init_two: function (xdata, ydata) { // Initialize the second chart this.storagemaxComponent.init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            setOption(chart, xdata, ydata)
            this.chart = chart;
            return chart;
        });
    },
    getOneOption: function () { //This step actually requires adding data to the chart var _this = this;
        wx.request({
            url: 'https://xxxxxxx.com', //The interface address where you request data method: 'POST',
            header: {
                "Content-Type": "application/json"
            },
            data: { // parameters passed, no need to say more about these id: xxxx
            },
            success:function(res){
     //I'm assuming here that res.xdata and res.ydata are the data we need, that is, the data displayed on the x-axis and y-axis. Remember that they must be arrays!
                _this.init_one(res.xdata,res.ydata)
            }
        })  
    },
    //The second chart is processed in the same way getTwoOption: function () {  
        var _this = this;
        wx.request({
            url: 'https://xxxxxxx.com', //The interface address where you request data method: 'POST',
            header: {
                "Content-Type": "application/json"
            },
            data: { // parameters passed, no need to say more about these id: xxxx
            },
            success:function(res){
                _this.init_two(res.xdata,res.ydata)
            }
        })  
    }
})

Okay, that's roughly the steps. If anything needs to change dynamically, just pass it in as a parameter. I cleared the timer in onUnload here, because if it's not clear, you will find that it will keep requesting when you jump to another page, so you have to clear the timer before leaving this page. I'm not a technical expert, so if there is a better way, I hope you can correct me! Hahaha

Summarize

This is the end of this article about WeChat Mini Program + ECharts to achieve dynamic refresh. For more relevant WeChat Mini Program + ECharts dynamic refresh content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use echarts in WeChat applet
  • Detailed explanation of how to use Echarts chart component in WeChat applet
  • WeChat applet uses echarts to obtain data and generate line charts
  • How to use ECharts to asynchronously load data in WeChat applet

<<:  Detailed tutorial on installing MySQL 8.0 from source code on CentOS 7.4

>>:  A brief discussion on the Linux kernel's support for floating-point operations

Recommend

Use a table to adjust the format of the form controls to make them look better

Because I want to write a web page myself, I am al...

Vue image cropping component example code

Example: tip: This component is based on vue-crop...

A brief discussion on how to choose and combine div and table

Page layout has always been my concern since I st...

Solution to Ubuntu not being able to connect to the Internet

Problem description: I used a desktop computer an...

Vue realizes screen adaptation of large screen pages

This article shares the specific code of Vue to a...

Markup Languages ​​- Lists Again

Click here to return to the 123WORDPRESS.COM HTML ...

Detailed tutorial for springcloud alibaba nacos linux configuration

First download the compressed package of nacos fr...

How to set up remote access to a server by specifying an IP address in Windows

We have many servers that are often interfered wi...

How to view the running time of MySQL statements through Query Profiler

The previous article introduced two methods to ch...

How to purchase and initially build a server

I haven't worked with servers for a while. No...

Methods and steps for deploying multiple war packages in Tomcat

1 Background JDK1.8-u181 and Tomcat8.5.53 were in...

js simple and crude publish and subscribe sample code

What is Publish/Subscribe? Let me give you an exa...

Html makes a simple and beautiful login page

Let’s take a look first. HTML source code: XML/HT...

JavaScript source code for Elimination

JavaScript to achieve the source code download ad...