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

(一)现状

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

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

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

(二)实现的代码

1、app.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、首页


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

你可能感兴趣的:(微信小程序,小程序)