微信小程序 Echarts 异步数据更新的练习,被坑了很多次,特作记录。

作者:罗兵

地址:https://www.cnblogs.com/hhh5460/p/9989805.html

0、效果图

               

1、视图

<!--index.wxml-->
<view class="container">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>

2、设置

//index.json
{
"usingComponents": {
"ec-canvas": "../../components/ec-canvas/ec-canvas"
}
}

3、样式

/**index.wxss**/
ec-canvas {
width: 100%;
height: 100%;
}
/**app.wxss**/
.container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0; display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
}

4、逻辑

/**index.js**/

// 载入组件
import * as echarts from '../../components/ec-canvas/echarts';
// 载入工具
//const util = require('../../utils/util.js') // 全局变量
let chart = null;
let month = ['月', '月', '月', '月', '月', '月']; //月份
let evaporation = [0, 0, 0, 0, 0, 0]; //蒸发量
let precipitation = [0, 0, 0, 0, 0, 0]; //降水量 function initChart(canvas, width, height) {
chart = echarts.init(canvas, null, {
width: width,
height: height
});
canvas.setChart(chart); chart.showLoading(); // 首次显示加载动画 var option = {
legend: {
data: ['蒸发量', '降水量']
},
xAxis: {
data: month //全局变量
},
yAxis: {},
series: [{
name: '蒸发量',
type: 'bar',
data: evaporation //全局变量
}, {
name: '降水量',
type: 'line',
data: precipitation //全局变量
}]
}; chart.setOption(option);
chart.hideLoading(); // 隐藏加载动画
return chart;
}; Page({
data: {
ec: {
onInit: initChart
},
lastid: 0 // 哨兵
}, onReady() {
this.data.timer = setInterval(this.getData, 2000);
}, getData() { //请求后台数据
var that = this;
wx.request({
url: 'http://127.0.0.1:5000/api/weather',
herder: {
"content-type": "application/json"
},
method: "POST",
data:{
id: that.data.lastid + 1 // 哨兵,记录上次数据表中的最后id
},
success: function(res){
that.setData({lastid: that.data.lastid + 1}); // 下面这三个骚操作受python启发!!
month = month.slice(1).concat(res.data.month); // 数组,先切片、再拼接
evaporation = evaporation.slice(1).concat(res.data.evaporation.map(parseFloat)); //注意map方法
precipitation = precipitation.slice(1).concat(res.data.precipitation.map(parseFloat)); chart.setOption({
xAxis: {
data: month //全局变量
},
series: [{
name: '蒸发量',
data: evaporation //全局变量
}, {
name: '降水量',
data: precipitation //全局变量
}]
}); if(that.data.lastid == 12){clearInterval(that.data.timer);}
},
fail: function (res) {},
complete: function (res) {},
});
} });

5、后端

# flask_restful_api.py

import sqlite3
from flask import Flask, request, render_template, jsonify app = Flask(__name__) def get_db():
db = sqlite3.connect('mydb.db')
db.row_factory = sqlite3.Row
return db def query_db(query, args=(), one=False):
db = get_db()
cur = db.execute(query, args)
db.commit()
rv = cur.fetchall()
db.close()
return (rv[0] if rv else None) if one else rv @app.before_first_request
def create_db():
# 建立连接
conn = sqlite3.connect('mydb.db')
c = conn.cursor()
# 创建表格
c.execute('''DROP TABLE IF EXISTS weather''')
c.execute('''CREATE TABLE weather (id integer, month text, evaporation text, precipitation text)''')
# 准备数据(格式:月份,蒸发量,降水量)
purchases = [(1,'1月', 2, 2.6),
(2, '2月', 4.9, 5.9),
(3,'3月', 7, 9),
(4,'4月', 23.2, 26.4),
(5,'5月', 25.6, 28.7),
(6,'6月', 76.7, 70.7),
(7,'7月', 135.6, 175.6),
(8,'8月', 162.2, 182.2),
(9,'9月', 32.6, 48.7),
(10,'10月', 20, 18.8),
(11,'11月', 6.4, 6),
(12,'12月', 3.3, 2.3)
]
# 插入数据
c.executemany('INSERT INTO weather VALUES (?,?,?,?)', purchases)
conn.commit()
conn.close() @app.route("/api/weather", methods=["GET","POST"])
def weather():
if request.method == 'POST':
res = query_db("SELECT * FROM weather WHERE id = (?)", args=(request.json['id'],)) #以后每次返回1个数据 return jsonify(month = [x[1] for x in res],
evaporation = [x[2] for x in res],
precipitation = [x[3] for x in res]) # 返回json格式 if __name__ == "__main__":
app.run(debug=True)

6、要点

a. 前端发送:herder: { "content-type": "application/json"};

前端接收:response.data(注意,微信将后台数据封装在res.data中, res.data是json格式)

b. 后端接收:request.json['id'] ;

后端发送:jsonify

c. 本地测试设置

7、参考

微信小程序Cannot read property 'setData' of null错误:https://blog.csdn.net/qq_42183184/article/details/82356208

微信小程序wx.request组件的那些坑:https://www.cnblogs.com/jhlqab/p/6900798.html

flask前端与后端之间传递的两种数据格式:json与FormData:https://www.cnblogs.com/hhh5460/p/8411978.html

flask+sqlite3+echarts3+ajax 异步更新数据:https://www.cnblogs.com/hhh5460/p/6010500.html

we3cschool微信小程序API发起请求:(地址略)

微信小程序 Echarts 异步数据更新的更多相关文章

  1. 微信小程序onlaunch异步,首页onLoad先执行?

    按照原理是小程序初始化时会先触发APP里的onLaunch事件,之后再执行页面Page里的onLoad事件.但实际请求时在onLaunch事件中请求获取数据,等待返回值的时候Page里的onLoad事 ...

  2. 微信小程序onLaunch异步,首页onLoad先执行?

    本来按照事件顺序,小程序初始化时触发App里的onLaunch,后面再执行页面Page里的onLoad,但是在onLaunch里请求获取是否有权限,等待返回值的时候Page里的onLoad事件就已经执 ...

  3. 微信小程序echarts层级太高

    项目中因为需求,底部的tab导航栏是自己写的,在开发者工具中一切正常:但是在真机上页面滑动时,echarts的层级比tab高,调过两者的z-index后仍然如此. 经过查找后发现cover-view和 ...

  4. 微信小程序异步处理

    直接看问题: 然后看打印的结果: 根据上面两图可以看出,代码上先执行的网络请求,再执行打印的变量,但是从下面打印的结果来看,先出结果的是执行打印变量的函数(aafn函数),再打印出网络请求succes ...

  5. 微信小程序之onLaunch与onload异步问题

    所述问题: 前端时间开发了一个微信小程序商城项目,因为这个项目我们的需求是进入小程序就通过wx.login({}) 这个api进行用户登录,获取系统后台的用户基本信息.再此之前,一直以为微信小程序中的 ...

  6. 微信小程序踩坑集合

    1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=1476434678461 2:简易教程:https://mp.weixin.qq.com/debu ...

  7. 微信小程序中同步 异步的使用

    https://www.jianshu.com/p/e92c7495da76   微信小程序中使用Promise进行异步流程处理 https://www.cnblogs.com/cckui/p/102 ...

  8. 微信小程序学习指南

    作者:初雪链接:https://www.zhihu.com/question/50907897/answer/128494332来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  9. 微信小程序学习记录(一)

    如何定义一个全局变量: 1,在根目录下app.js中添加 App({ globalData: { g_isPlayingMusic : false, g_currentMusicPostId :nul ...

随机推荐

  1. 常用的第三方模块 Pillow url

    Pillow PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了.PIL功能非常强大,但API却非常简单易用. 由于PIL仅支持到Python 2.7 ...

  2. 【Python】读取excel数据

    '''python3读取excle数据''' import xlrd workbook = xlrd.open_workbook(r'test.xls', encoding_override='gbk ...

  3. python websocket client 使用

    import websocket ws = websocket.WebSocket() ws.connect("xx.xx.xx") ws.send("string&qu ...

  4. APP性能测试指标和测试方法

    流量 常用方法 方法一:Android系统自带统计功能(总体流量数值) Proc/uid_stat/{UID}/tcp_snd和tcp_rcv UID是每个app安装时候分配的唯一编号用于识别该app ...

  5. PHP剔除删除掉危险字符

    本文出至:新太潮流网络博客 /** * [剔除掉危险字符] * @E-mial wuliqiang_aa@163.com * @TIME 2017-04-07 * @WEB http://blog.i ...

  6. 购物商城学习--第二讲(maven工程介绍)

    接下来第二讲介绍整体工程如何使用maven搭建的. 使用maven管理工程的好处: jar包的管理: 工程之间的依赖管理: 自动打包 maven常见打包方式:jar.war和pom三种.jar工程,是 ...

  7. centos7 修改中文字符集

    CentOS 7字符集的问题与6有点区别,会出现下面问题,查看是中文,vi进入就变成乱码了 生产中修改配置文件   [root@ce1d2002a999 ~]# cat /etc/locale.con ...

  8. PowerShell下载文件

    $webRequest = [System.Net.HttpWebRequest]::Create("http://go.microsoft.com/fwlink/?LinkID=14915 ...

  9. months_between()用法

    orcl中months_between()函数用法如下: 格式:即MONTHS_BETWEEN(日期1,日期2) 例如: select months_between(to_date('2018-10- ...

  10. wing ide 6.0 注册

    1.wing ide介绍 wing ide ,用过python的都知道是干嘛用的了吧,官网已经更新到6.0.0-1版本. 链接如下: Wing IDE Professional - Version 6 ...