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

MySQL index usage instructions (single-column index and multi-column index)

1. Single column index Choosing which columns to ...

HTML page jump passing parameter problem

The effect is as follows: a page After clicking t...

Detailed installation and use of SSH in Ubuntu environment

SSH stands for Secure Shell, which is a secure tr...

Interaction in web design: A brief discussion on paging issues

Function: Jump to the previous page or the next p...

CSS implements 0.5px lines to solve mobile compatibility issues (recommended)

【content】: 1. Use background-image gradient style...

Common considerations for building a Hadoop 3.2.0 cluster

One port changes In version 3.2.0, the namenode p...

Detailed explanation of Docker data backup and recovery process

The data backup operation is very easy. Execute t...

HTML weight loss Streamline HTML tags to create web pages

HTML 4 HTML (not XHTML), MIME type is text/html, ...

JS achieves five-star praise effect

Use JS to implement object-oriented methods to ac...

Comparative Analysis of IN and Exists in MySQL Statements

Background Recently, when writing SQL statements,...

mysql method to recursively search for all child nodes of a menu node

background There is a requirement in the project ...

Why MySQL can ignore time zone issues when using timestamp?

I have always wondered why the MySQL database tim...