微信小程序:全局状态管理mobx-miniprogram

简介: 微信小程序:全局状态管理mobx-miniprogram

安装

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

定义 store.js

/**
 * 全局状态管理
 */
import { observable, action } from 'mobx-miniprogram';
export const store = observable({
  // 数据字段
  numA: 1,
  numB: 2,
  // 计算属性
  get sum() {
    return this.numA * this.numB;
  },
  // actions
  update: action(function () {
    this.numA++;
  }),
});

在 Component 构造器中使用

import{ storeBindingsBehavior }from'mobx-miniprogram-bindings'
import{ store }from'./store'
Component({
  // behavior 绑定
  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 构造器中使用:

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 的字段
  }
})

在 app.js 中使用

import { store } from './store';
App({
    onShow(options) {
        // 更新
        store.update();
  },
})

参考

https://www.bookstack.cn/read/miniprogram-extended/54620b3fcfec59b9.md


相关文章
|
边缘计算 人工智能 安全
探索边缘计算:定义、优势及未来趋势
探索边缘计算:定义、优势及未来趋势
|
机器学习/深度学习 人工智能 前端开发
【人工智能】利用TensorFlow.js在浏览器中实现一个基本的情感分析系统
使用TensorFlow.js在浏览器中进行情感分析是一个非常实用的应用场景。TensorFlow.js 是一个用于在JavaScript环境中训练和部署机器学习模型的库,使得开发者能够在客户端直接运行复杂的机器学习任务。对于情感分析,我们可以使用预先训练好的模型来识别文本中的积极、消极或中性情感。
463 4
【人工智能】利用TensorFlow.js在浏览器中实现一个基本的情感分析系统
|
JSON 小程序 前端开发
终于搞懂了!微信小程序的渲染机制及组件使用
【8月更文挑战第8天】微信小程序的渲染机制及组件使用
925 3
终于搞懂了!微信小程序的渲染机制及组件使用
|
小程序 开发工具 Android开发
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(二)
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(二)
1073 0
|
JavaScript 定位技术
【天地图】vue 天地图 T is not defined
【天地图】vue 天地图 T is not defined
464 1
|
API Go 网络架构
Kratos 大乱炖 —— 整合其他Web框架:Gin、FastHttp、Hertz
Kratos默认的RPC框架使用的是gRPC,支持REST和protobuf两种通讯协议。其API都是使用protobuf定义的,REST协议是通过[grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway)转译实现的。使用protobuf定义API是具有极大优点的,具有很强的可读性、可维护性,以及工程性。工程再大,人员再多,也不会乱。 一切看起来都是很美好的。那么,问题来了,我们现在使用的是其他的Web框架,迁移就会有成本,有风险,不可能一下子就把历史存在的代码一口气转换过来到Kratos框架。那我可以在Kratos中整合其他
1222 0
|
存储 小程序 JavaScript
【微信小程序】-- 全局数据共享 - MobX(四十三)
【微信小程序】-- 全局数据共享 - MobX(四十三)
|
前端开发
多个前端项目中公共组件使用方案(npm包方式)
多个前端项目中公共组件使用方案(npm包方式)
多个前端项目中公共组件使用方案(npm包方式)
|
JSON 小程序 JavaScript
小程序学习笔记 | 如何实现左滑删除效果?
小程序学习笔记 | 如何实现左滑删除效果?