Day 281/300 微信小程序 监听接口返回的数据后 动态赋值并展示

(一)现状

1、一开始使用的缓存+setTimeout,缺点是不知道什么时候回来;网络速度慢的时候,会有空白的情况,或者是需要连续发,不太好;

2、想实现监听接口返回的数据后 动态赋值并展示的效果;

还可以用 状态管理的方式,mobx-miniprogram

(二)实现的代码

1、app.ts

ts 复制代码
// app.ts
App<IAppOption>({
  globalData: {
    setting: 'prod', // prod  dev
  },
  // 监听全局变量变化
  watch: function (variate, method) {
    var obj = this.globalData;
    let val = obj[variate]; // 单独变量来存储原来的值
    Object.defineProperty(obj, variate, {
      configurable: false,
      enumerable: true,
      set: function (value) {
        val = value; // 重新赋值
        method(variate, value); // 执行回调方法
      },
      get: function () {
        // 在其他界面调用getApp().globalData.variate的时候,这里就会执行。
        return val; // 返回当前值
      }
    })
  },
  onLaunch() {
    const that = this
    // 登录
    wx.login({
      success: res => {
        // console.log('code---',res.code)
        if(!wx.getStorageSync("token")){
          wx.request({
            url: this.globalData.url + '/login',
            method: 'GET',
            data: {
              "code":res.code
            },
            header: {
              'content-type': 'application/json'
            },
            success (res) {
              const response = res.data.data
              const token = response && response.user_setting && response.user_setting.token || ''
              const template = response && response.user_setting && response.user_setting.template || []
              const balance = response && response.user_setting && response.user_setting.balance || []
              that.globalData.template = template;
              that.globalData.balance = balance;
              wx.setStorageSync("token",token)
              wx.setStorageSync("template",template)
              wx.setStorageSync("balance",balance)
            }
          })
        }
      },
    })

  },
})

2、首页

ts 复制代码
Page({
  data: {
    balance: '',
  },
  watchCallBack(name: string, value: any) {
    // console.log('watchBack', name, value);
    if (name === 'balance') {
      this.setData({
        balance: value,
      });
    }
  },
  onLoad() {
    // @ts-ignore
    getApp().watch('balance', this.watchCallBack)
  },
  onReady() {
    
  },
  onShow() {

  },
})

参考链接

https://juejin.cn/post/7241101553712955451

相关推荐
WangHappy16 小时前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端21 小时前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker2 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者5 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround6 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround6 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌6 天前
小程序——布局示例
小程序
码云数智-大飞6 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54596 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序