微信小程序-外部JS修改当前页面内容

微信小程序提供了数据绑定,通过setData()函数,可以在页面对应的js内实现修改前端界面内容。但是如果在外部js函数体中如果有异步网络请求,则不能通过返回值的方式传参了。
这种情况下,只需要将本页面对象通过参数传到外部函数,在外部函数中调用setData()即可,类似C++中的引用(事实上则本来就是引用传值)。

// index.js 页面

const tencentcloud = require("../../iotsdk/lotsdk.js");
Page({
  //调用外部函数
  pullShadow: function () {
    tencentcloud.deviceData(this) //page传出去
  }
})

// 外部js函数 iotsdk.js

function GetDeviceData(page) {
  // 实例化要请求产品的client对象
  let client = new lotclient(SECRETID, SECRETKEY);
  // 实例化一个请求对象
  let req = new lotmodel.DescribeDeviceDataRequest();
  req.DeviceName = DEVICENAME;
  req.ProductId = PRODUCTID;
  // 通过client对象调用想要访问的接口,需要传入请求对象以及响应回调函数
  client.DescribeDeviceData(req, function (err, response) {
    // 请求异常返回,打印异常信息,并重新发送请求直到成功
    if (err) {
      console.log("failed:" + err);
      return GetDeviceData(page)
    } else {
      // 请求正常返回,打印response对象
      console.log("ControlDeviceData success");
      page.setData({ shadow: JSON.parse(response.Data) })
    }
  });
}
module.exports = {
  deviceHistory: GetDeviceHistory
}
发布了24 篇原创文章 · 获赞 8 · 访问量 7216

猜你喜欢

转载自blog.csdn.net/geek_hch/article/details/99457157
今日推荐