一、下载mobx相关包
npm i -S mobx-miniprogram mobx-miniprogram-bindings
注意:下载完成后,需要删除 miniprogram_npm 目录后,重新构建 npm。
二、创建是 MobX的store实例
注意:ts编写的话,方法中使用this,需要在参数中定义this: any,否则会提示错误
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;
})
});
三、页面使用store
引入onLoad()方法中引入createStoreBindings将store上的方法和属性绑定到页面中
在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'], //数组方式
fields:{
numA: 'numA',
numB: ()=> store.numB,
sum: (store:any) => store.sum
}, //对象形式
actions:['updateNumA']
});
},
onUnload(this:any){
this.storeBinding.destroyStoreBindings();
}
})
页面中使用:
<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项目使用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);
},
}
})
自定义组件:文章来源:https://www.toymoban.com/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>
页面组引入自定义组件:文章来源地址https://www.toymoban.com/news/detail-561714.html
<view>
{{numA}} + {{numB}} = {{sum}}
</view>
<!-- 自定义组件中使用store -->
<store-test></store-test>
到了这里,关于微信小程序TS项目使用mobx(页面直接使用store和自定义组件中使用store)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!