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

8次阅读

共计 1914 个字符,预计需要花费 5 分钟才能阅读完成。

点击返回小程序 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()(在 手工绑定 中)
正文完
 0