插件简介
mobx-miniprogram: 用来创建Store对象
mobx-miniprogram-bindings:用来把Store中的共享数据或方法,绑定到页面或者组件中使用
安装 npm i --save mobx-miniprogram mobx-miniprogram-bindings
创建Store对象
import {
observable,
action
} from "mobx-miniprogram";
export const store = observable({
count: 0,
get double() {
return this.count * 2
},
increase: action(function (num) {
this.count += num
})
})
在页面上使用
import {
createStoreBindings
} from "mobx-miniprogram-bindings"
import { store } from '../../store/index.js'
Page({
onLoad() {
this.storeBindings = createStoreBindings(this, {
store,
fields: ['count', 'double'],
actions: ['increase']
})
},
click() {
this.increase(1)
},
onUnload() {
this.storeBindings.destroyStoreBindings();
}
})
<view class="container log-list">
<text>全局数据{{count}}</text>
<text>全局计算属性{{double}}</text>
<van-button type="default" bindtap="click">默认按钮</van-button>
</view>
在组件使用
import {
storeBindingsBehavior
} from "mobx-miniprogram-bindings"
import { store } from "../../store/index.js"
Component({
behaviors: [storeBindingsBehavior],
storeBindings: {
store,
fields: ['count'],
actions: ['increase']
},
methods: {
increaseHandle() {
this.increase(1)
}
}
})
<view>
{{count}}
<van-button type="default" bindtap="increaseHandle">组件+1</van-button>
</view>
映射数据和方法的其他方式(以组件为例,页面一样)
import {
storeBindingsBehavior
} from "mobx-miniprogram-bindings"
import { store } from "../../store/index.js"
Component({
behaviors: [storeBindingsBehavior],
storeBindings: {
store,
fields: {
countA: "count",
countB: () => store.count,
countC: (store) => store.count,
},
actions: {
increaseF: "increase"
}
}
})
模块化
- 模块
import {observable,action} from 'mobx-miniprogram'
export default observable({
count:1,
setNum:action(function(num){
this.count+=num
})
})
- index
import tabBarStore from './module/tabBarStore'
const store = Object.assign({}, tabBarStore)
export default store
- 使用方法与非模块化的方法一样
westore实现数据共享