微信小程序API的Promise化及全局状态管理MobX

API的Promise化

默认情况下小程序官方提供的API都是基于回调函数实现的,例如

wx.request({
    
    
	method:'',
	url:'',
	data:{
    
    },
	success:()=>{
    
    },
	fail: ()=>{
    
    },
	complete: ()=>{
    
    }
})

为了避免回调地狱的问题,我们将小程序的API Promise化

小程序中的Promise主要依赖于miniprogram-api-promise三方npm包

每次装完新包要记得重新构建npm,同时建议重新构建前先删除miniprogram_npm这个文件

创建promise化的对象

// app.js
import {
    
    promisifyAll} from 'miniprogram-api-promise'
// 创建wxp和wx.p用于存放封装好的api
const wxp = wx.p = {
    
    }
promisifyAll(wx,wxp)

全局状态管理

即解决组件之间数据共享的问题,常用的全局共享解决方案有:Vuex、Redux、MobX等

在小程序中,我们使用mobx-miniprogram配合mobx-miniprogram-bindings实现全局数据共享

  • mobx-miniprogram用于创建store实例对象
  • mobx-miniprogram-bindings用于将store中的共享数据或方法,绑定到组件或页面中使用
npm i --save [email protected] [email protected]

创建

在根目录创建store文件夹,内部含store.js

// 该文件用于创建store实例
import {
    
    action, observable} from 'mobx-miniprogram'

export const store = observable({
    
    
  // 数据字段
  numA: 1,
  numB: 2,
  // 计算属性
  get sum(){
    
    
    return this.numA + this.numB
  },
  // actions
  updateNumA: action(function(step){
    
    
    this.numA += step
  })
})

页面中绑定

  1. 导入
  2. onLoad周期进行绑定
  3. onUnload周期进行清理
import {
    
    createStoreBindings} from 'mobx-miniprogram-bindings'
import {
    
    store} from '../../store/store'

onLoad: function (options) {
    
    
  // createStoreBindings(实例,配置对象)
  // 配置对象:store数据源;fields数据;actions方法
  this.storeBindings = createStoreBindings(this,{
    
    
    store,
    fields:['numA','numB','sum'],
    actions:['updateNumA']
  })
},
onUnload: function () {
    
    
  this.storeBindings.destroyStoreBindings()
},

页面中使用

<view>{
   
   {numA}} + {
   
   {numB}} = {
   
   {sum}}</view>
<van-button type="primary" bindtap="btnClick" data-step="{
     
     {1}}"> numA+1 </van-button>
<van-button type="danger" bindtap="btnClick" data-step="{
     
     {-1}}"> numA-1 </van-button>
btnClick(e){
    
    
  this.updateNumA(e.target.dataset.step)
},

组件中绑定

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"
    }
  }
})

组件中使用

同页面的使用方法

猜你喜欢

转载自blog.csdn.net/qq_47234456/article/details/128908095