【小程序基础】使用npm包

361 阅读1分钟

API Promise 化

安装依赖

npm i miniprogram-api-promise@1.0.4

app.js 调用promisifyAll

// app.js
import { promisifyAll } from 'miniprogram-api-promise'
const wxp = wx.p = {}
promisifyAll(wx, wxp)

页面中使用

async getInfo() {
    const {data: res} = await wx.p.request({
      method: 'GET',
      url: 'https://www.escook.cn/api/get',
      data: {
        name: 'zs',
        age: 20
      }
    })
    console.log(res)
}

全局数据共享

依赖包

在小程序中,可使用 mobx-miniprogram 配合 mobx-miniprogram-bindings 实现全局数据共享。其中:

  • mobx-miniprogram 用来创建 Store 实例对象
  • mobx-miniprogram-bindings 用来把 Store 中的共享数据或方法,绑定到组件或页面中使用

创建 MobX 的 Store 实例

// store/store.js
import { observable, action } from 'mobx-miniprogram'
export const store = observable({
  // 数据字段
  numA: 1,
  numB: 2,
  // 计算属性
  get sum() {
    return this.numA + this.numB
  },
  // action方法,用来修改store中的字段值
  updateNumA: action(function (step) {
    this.numA += step
  }),
  updateNumB: action(function (step) {
    this.numB += step
  })
})

在页面中使用

// pages/index/index.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
  data: {
  },
  onLoad: function (options) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: ['numA', 'numB', 'sum'],
      actions: ['updateNumA']
    })
  },
  onUnload: function () {
    this.storeBinding.destroyStoreBingdings()
  },
  btnHandler1: function (e) {
    this.updateNumA(e.target.dataset.step)
  }
})
<!--pages/index/index.wxml-->
<view>{{numA}} + {{numB}} == {{sum}}</view>
<button bindtap="btnHandler1" data-step="{{1}}">+1</button>
<button bindtap="btnHandler1" data-step="{{-1}}">-1</button>

在组件中使用

// components/numbers/numbers.js
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store,
    fields:{
      numA: () => store.numA,
      numB: (store) => store.numB,
      sum: 'sum'
    },
    actions:{
      'updateNumB': 'updateNumB'
    }
  },
  properties: {
  },
  data: {
  },
  methods: {
    btnHandler1(e) {
      this.updateNumB(e.target.dataset.step)
    }
  }
})

<!--components/numbers/numbers.wxml-->
<view>{{numA}} + {{numB}} == {{sum}}</view>
<button bindtap="btnHandler1" data-step="{{1}}">+1</button>
<button bindtap="btnHandler1" data-step="{{-1}}">-1</button>