微信小程序TS项目使用mobx(页面直接使用store和自定义组件中使用store)

一、下载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);
    },
  }
})

自定义组件:

<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>

页面组引入自定义组件:

<view>
  {
   
   {numA}} + {
   
   {numB}} = {
   
   {sum}}
</view>
<!-- 自定义组件中使用store -->
<store-test></store-test>

猜你喜欢

转载自blog.csdn.net/qq_34569497/article/details/130781583