When using mobx in a mini program, the connect
function can efficiently bind the observed data to the mini program view. See v1 for the old inject
method
npm install mobx-wxapp
installs the project locally or directly copies the file (example/mobx-wxapp.js) to your project.
(The case uses mobx.js v4.6.0, because mobx5 uses ES6 proxy, which is not currently supported by the mini program)
pages/index.js:
import { connect , extract } from '../mobx-wxapp'
import { observable } from '../mobx'
const appStore = observable ( {
title : 'mobx-wxapp'
} )
const store = observable ( {
// observable
seconds : 0 ,
// computed
get color ( ) {
return this . seconds % 2 ? 'red' : 'green'
} ,
// actions
tick ( ) {
this . seconds += 1
}
} )
// page
Page ( {
onLoad ( ) {
connect ( this , ( ) => ( {
title : appStore . title ,
color : store . color ,
seconds : store . seconds
// 或者使用 extract 一次性提取全部属性
// ...extract(store)
} )
)
} ,
add ( ) {
store . tick ( )
}
} )
pages/index.wxml:
< view >{{ title }} :</ view >
< view style = " color:{{ color }} " > seconds:{{ seconds }} </ view >
< button bindtap = " add " >add</ button >
Of course, you can also use it in Component:
Component ( {
//..
ready ( ) {
this . disposer = connect ( this , mapDataToStore , options )
} ,
//请务必在组件生命周期结束前执行销毁器!
detached ( ) {
this . disposer ( ) ;
}
//...
} )
options = {
delay:Number,// setData的最小执行间隔,默认30ms
setDataCallback:Function // setData的执行回调
}
Return value: connect
returns a destroyer function (when used in Page, it will be automatically executed in the onUnload life cycle, but when used in the Component constructor, please make sure to call this function manually at the end of the life cycle).
Shortcut to map the entire store
Return value: an object that can be mapped to data
ISC licensed.