小程序中使用 MobX 绑定辅助库

点击前往小程序MobX的官方文档

注:此 behavior 依赖开发者工具的 npm 构建。 什么是npm构建?

安装 mobx-miniprogrammobx-miniprogram--bindings

npm install --save mobx-miniprogram mobx-miniprogram-bindings

点击微信开发者工具左上角:工具 --- npm 构建

构建完成后,两个文件夹下 mobx-xxxxx 的4个包都已经就绪

小程序中使用 MobX 绑定辅助库_第1张图片

创建 MobX Store:新建store.js,并实例化 observable

observable 是默认的 MobX store

小程序中使用 MobX 绑定辅助库_第2张图片

// store.js
import { observable, action } from 'mobx-miniprogram'

// 创建store并暴露出去
// observable:默认的 MobX store
export const store = observable({

  // 数据data
  numA: 1,
  numB: 2,

  // 计算属性
  get sum() {
    return this.numA + this.numB
  },

  // 通过 action 声明
  update: action(function () {
    const sum = this.sum
    this.numA = this.numB
    this.numB = sum
  })
})

store创建好了,接下来就是怎么绑定的问题了

绑定配置

无论使用哪种绑定方式,都必须提供一个绑定配置对象,参数如下:

  • store:默认的 MobX store
  • fields:用于指定需要绑定的 data 字段。数组或者对象(数组、映射、函数)
  • actions: 用于指定需要映射的 actions。数组或者对象(数组、映射)

废话不多说,直接看例子

手工绑定:通过 createStoreBindings (适用于全部场景)

注意: 在页面 onUnload (自定义组件 detached )时一定要调用清理函数 destroyStoreBindings,否则将导致内存泄漏!

// page.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from './../../store/store'

Page({
  data: {
  },
  onLoad() {
      // 传入指针 this 实例化
    this.storeBindings = createStoreBindings(this, {
      store,
      // 数组形式需要与data同名
      fields: ['numA', 'numB', 'sum'], 
      actions: ['update'], 
    })
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },
  // 可以在method的合适时机,去调用update
  myMethod() {
    this.update()
  }
})

store中的 numA numB sumupdatepage.js 和对应的 page.wxml 中 即可正常使用

behavior绑定:通过storeBindingsBehavior(适用于 Component 构造器)

// component.js
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../../store/store'

Component({
  // 固定写法
  behaviors: [storeBindingsBehavior],
  data: {
    someData: '...'
  },
  
  storeBindings: {
    store,
    // 函数形式,可另外声明变量
    fields: {
      numA: () => store.numA,
      numB: (store) => store.numB,
      sum: 'sum'
    },
    // 映射形式,可另外声明变量
    actions: {
      buttonTap: 'update'
    },
  },
  methods: {
    add() {
      // buttonTap 即 update
      this.buttonTap()
    }
  }
})

fields、actions如果使用数组,需要与store中同名;如果使用对象,可单独声明变量

延迟更新与立刻更新

为了提升性能,在 store 中的字段被更新后,并不会立刻同步更新到 this.data 上,而是等到下个 wx.nextTick 调用时才更新。(这样可以显著减少 setData 的调用次数。)
如果需要立刻更新,可以调用:

  • this.updateStoreBindings() (在 behavior 绑定 中)
  • this.storeBindings.updateStoreBindings() (在 手工绑定 中)

你可能感兴趣的:(微信小程序小程序mobx前端)