关于微信小程序:小程序中使用-MobX-绑定辅助库

点击返回小程序MobX的官网文档

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

装置 mobx-miniprogrammobx-miniprogram--bindings

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

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

构建实现后,两个文件夹下 mobx-xxxxx 的4个包都曾经就绪

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

observable 是默认的 MobX store

// 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() (在 手工绑定 中)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理