Mobx-miniprogram and MOBx-miniprogram-Bindings can be used in small programs for state management (global data management).

Install dependencies

npm i -S mobx-miniprogram mobx-miniprogram-bindings

Creating a global object

Create a store folder in the root directory of the project to store files related to status management. Create a store.js file to store global data:

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

export const store = observable({
  num1: 1.num2: 2
})
Copy the code

Defining computed properties

Similar to the getter in VUex.

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

export const store = observable({
  num1: 1.num2: 2.get sum() {// Calculate the attribute, num1 and num2 when using sum
    return this.num1 + this.num2 
  }
})
Copy the code

Modify data in store

Use action to modify the data in the Store.

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

export const store = observable({
  num1: 1.num2: 2.get sum() {return this.num1 + this.num2
  },
  updateNum1: action(function(step){  The first argument to the function is the argument passed when the action is triggered
    thjis.num1 += step
  })
})
Copy the code

Page to get data from the store

Store and createStoreBindings methods are introduced to bind global data to a page. You only need to use Mustache syntax in your WXML file.

// home page home.js

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

Page({
  onLoad: function (options) {
    this.storeBindings = createStoreBindings(this,{
      store,                          / / into the store
      fields: ['num1'.'num2'.'sum'].// What data is required here
      actions: ['updateNum1']          Actions this.updateNum1 triggers the action})},onUnload: function () {
    this.storeBindings.destroyStoreBingdings()  // Destroy the data binding when the page is unmounted}})Copy the code

Component to get data from the store

Very similar to using in pages.

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

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store,
    fields: {
      num1: 'num1'.num2: 'num2'.sum: 'sum'
    },
    actions: {
      updateNum1: 'updateNum1'}}})Copy the code