一、下載mobx相關(guān)包
npm i -S mobx-miniprogram mobx-miniprogram-bindings
?注意:下載完成后,需要?jiǎng)h除 miniprogram_npm 目錄后,重新構(gòu)建 npm。
二、創(chuàng)建是 MobX的store實(shí)例
注意:ts編寫的話,方法中使用this,需要在參數(shù)中定義this: any,否則會(huì)提示錯(cuò)誤
import { observable, action} from 'mobx-miniprogram'
export const store = observable({
numA: 1,
numB: 2,
get sum(){
return this.numA + this.numB;
},
updateNumA: action(function(this: any, step:number){
this.numA += step;
}),
updateNumB: action(function(this: any, step:number){
this.numB += step;
})
});
三、頁(yè)面使用store
引入onLoad()方法中引入createStoreBindings將store上的方法和屬性綁定到頁(yè)面中
在unOnLoad()方法中銷毀destroyStoreBindings()
// 引入store
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "../../store/store"
Page({
data: {
},
handleNum(this:any, e:any){
this.updateNumA(e.target.dataset.step-0);
},
onLoad(this:any) {
this.storeBinding = createStoreBindings(this,{
store,
// fields:['numA','numB','sum'], //數(shù)組方式
fields:{
numA: 'numA',
numB: ()=> store.numB,
sum: (store:any) => store.sum
}, //對(duì)象形式
actions:['updateNumA']
});
},
onUnload(this:any){
this.storeBinding.destroyStoreBindings();
}
})
頁(yè)面中使用:
<view>
{{numA}} + {{numB}} = {{sum}}
</view>
<van-button type="primary" bindtap="handleNum" data-step="1">update numA</van-button>
<van-button type="info" bindtap="handleNum" data-step="-1">update numA</van-button>
四、自定義組件中使用store
在自定義組件ts文件中引入ComponentWithStore,注意如果是TS必須使用ComponentWithStore,如果是js項(xiàng)目使用storeBindingsBehavior
// components/store-test/store-test.ts
// import { storeBindingsBehavior} from 'mobx-miniprogram-bindings'
// ts中使用mobx和js中不一樣,js中使用storeBindingsBehavior,ts中使用ComponentWithStore
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
ComponentWithStore({
storeBindings: {
store: store,
fields: ["numA", "numB", "sum"],
actions: {
updateNumB: "updateNumB",
},
},
/**
* 組件的方法列表
*/
methods: {
handleNumB(this:any, e:any){
console.log(this);
this.updateNumB(e.target.dataset.step-0);
},
}
})
自定義組件:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-561714.html
<van-button type="primary" bindtap="handleNumB" data-step="1">update numB</van-button>
<van-button type="info" bindtap="handleNumB" data-step="-1">update numB</van-button>
頁(yè)面組引入自定義組件:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-561714.html
<view>
{{numA}} + {{numB}} = {{sum}}
</view>
<!-- 自定義組件中使用store -->
<store-test></store-test>
到了這里,關(guān)于微信小程序TS項(xiàng)目使用mobx(頁(yè)面直接使用store和自定義組件中使用store)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!