微信小程序中的vuex(MobX)

相信大家可能在vue项目中通过vuex来实现各种项目的数据的存储,以及实现多组件,多页面之间的通信,然后,后面开始接触小程序开发,以后站在vue角度上很好解决的问题,在微信小程序中就犯了难,如果想要了解微信小程序之间的通信可以去看我之前的文章,微信小程序中的数据传值,今天主要给大家分享一波微信小程序中Mobx的使用,类似vuex的状态管理工具。

一、安装所需配置(mobx-miniprogram 和 mobx-miniprogram-bindings

npm install --save mobx-miniprogram mobx-miniprogram-bindings

二、搭建MobX Store管理仓库

// store.js  引入所需配置
import { observable, action } from "mobx-miniprogram";

//创建仓库
export const store = observable({
  // 数据字段
  numA: 1,
  numB: 2,

  // 计算属性 数据改变时会执行,vue中的计算属性,返回sum这个变量
  get sum() {
    return this.numA + this.numB;
  },

  // actions 方法用于改变仓库的值
  update: action(function () {
    const sum = this.sum;
    this.numA = this.numB;
    this.numB = sum;
  }),
});

三、在 Component 构造器中使用:

//引入相关配置
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
//引入组件库
import { store } from "./store";

Component({
  behaviors: [storeBindingsBehavior],
  data: {
    someData: "...",
  },
  storeBindings: {
    store,
//对应值,页面显示值
    fields: {
      numA: () => store.numA,
      numB: (store) => store.numB,
      sum: "sum",
    },
//触发方法
    actions: {
      buttonTap: "update",
    },
  },
  methods: {
    myMethod() {
//获取仓库值
      this.data.sum; // 来自于 MobX store 的字段
    },
  },
});

四、在 Page 构造器中使用:

如果小程序基础库版本在 2.9.2 以上,可以直接像上面 Component 构造器那样引入 behaviors 。

如果需要比较好的兼容性,可以使用下面这种方式(或者直接改用 Component 构造器来创建页面)。

import { createStoreBindings } from "mobx-miniprogram-bindings";
import { store } from "./store";

Page({
  data: {
    someData: "...",
  },
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ["numA", "numB", "sum"],
      actions: ["update"],
    });
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings();
  },
  myMethod() {
    this.data.sum; // 来自于 MobX store 的字段
  },
});

五、Typescript 支持

从 2.1.2 版本开始提供了简单的 TypeScript 支持。

新增两个构造器 API,推荐优先使用下列新版接口,你也可以继续使用旧版接口,详见接口说明。

ComponentWithStore

import { ComponentWithStore } from "mobx-miniprogram-binding";
ComponentWithStore({
  options: {
    styleIsolation: "shared",
  },
  data: {
    someData: "...",
  },
  storeBindings: {
    store,
    fields: ["numA", "numB", "sum"],
    actions: {
      buttonTap: "update",
    },
  },
});

BehaviorWithStore

import { BehaviorWithStore } from "mobx-miniprogram-binding";
export const testBehavior = BehaviorWithStore({
  storeBindings: {
    store,
    fields: ["numA", "numB", "sum"],
    actions: ["update"],
  },
});

了解更多请看    mobx

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值