小程序全局数据共享

为了解决组件之间数据共享的问题

安装包

小程序全局数据共享需要使用到两个 npm 包

1
npm i mobx-miniprogram mobx-miniprogram-bindings -S
  • mobx-miniprogarm:用来创建 Store 对象
  • mobx-miniprogarm-bindings:把 Store 对象中的数据和方法绑定到组件或页面上

创建实例对象

在项目根目录下创建 store 文件夹,全部的 mobx 相关的文件都需要放在这个文件夹中

在 store 文件夹中创建 store.js

1
2
3
4
5
import {
observable
} from 'mobx-miniprogram'

export const store = observable({})

创建数据和方法

数据

1
2
3
4
5
6
7
import {
observable
} from 'mobx-miniprogram'

export const store = observable({
num: 0
})

计算属性

1
2
3
4
5
6
7
8
9
10
11
import {
observable
} from 'mobx-miniprogram'

export const store = observable({
num: 0,

get increase() {
return this.num++
}
})

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
import {
observable,
action
} from 'mobx-miniprogram'

export const store = observable({
num: 0,

updateNum: action(function(num) {
this.num += num
})
})

绑定数据和方法

在页面组件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import {
createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
store
} from "../../store/store";

Page({
onLoad: function (options) {
/* 创建 */
this.storeBindings = createStoreBindings(this, {
store,
fields: ['num', 'increase'],
actions: ['updateNum']
}),
},

onUnload: function (
/* 卸载 */
this.storeBindings.destroyStoreBindings()
},
})
  • createStoreBindings:创建实例对象

    • 第一个参数(this):指代当前组件实例对象
    • 第二个人参数:配置项
      • store:数据源
      • fields:需要导入的数据或计算属性
      • actions:需要导入的方法
  • destroyStoreBindings:卸载实例对象

在自定义组件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import {
storeBindingsBechaviors
} from 'mobx-miniprogram-bindings'
import {
store
} from "../../store/store";

Component({
bechaviors: [storeBindingsBechaviors],
storeBindings: {
fieids: {
// 第一种方法
num: () => store.num
// 第二种方法
num: (store) => store.num
// 第三种方法
num: 'num'
},
actions: {
upodateNum: 'upodateNum'
}
}
})