mobx全局数据共享

449 阅读1分钟

插件简介

  1. mobx-miniprogram: 用来创建Store对象
  2. mobx-miniprogram-bindings:用来把Store中的共享数据或方法,绑定到页面或者组件中使用

安装 npm i --save mobx-miniprogram mobx-miniprogram-bindings

创建Store对象

// store/index.js
import {
    observable,
    action
} from "mobx-miniprogram";
export const store = observable({
    count: 0,
    get double() {
        return this.count * 2
    },
    increase: action(function (num) {
        this.count += num
    })
})

在页面上使用

import {
    createStoreBindings
} from "mobx-miniprogram-bindings"
import { store } from '../../store/index.js'

Page({
    onLoad() {
        // 创建
        this.storeBindings = createStoreBindings(this, {
            store,
            fields: ['count', 'double'],
            actions: ['increase']
        })
    },
    click() {
        // 使用
        this.increase(1)
    },
    onUnload() {
        // 清理
        this.storeBindings.destroyStoreBindings();
    }
})
<view class="container log-list">
    <!-- 使用 -->
    <text>全局数据{{count}}</text>
    <text>全局计算属性{{double}}</text>
    <van-button type="default" bindtap="click">默认按钮</van-button>
</view>

在组件使用

import {
    storeBindingsBehavior
} from "mobx-miniprogram-bindings"
import { store } from "../../store/index.js"

Component({
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: ['count'],
        actions: ['increase']
    },
    methods: {
        increaseHandle() {
            this.increase(1)
        }
    }
})
<view>
    {{count}}
    <van-button type="default" bindtap="increaseHandle">组件+1</van-button>
</view>

映射数据和方法的其他方式(以组件为例,页面一样)

import {
    storeBindingsBehavior
} from "mobx-miniprogram-bindings"
import { store } from "../../store/index.js"

Component({
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            countA: "count",
            countB: () => store.count,
            countC: (store) => store.count,
        },

        actions: {
            increaseF: "increase"
        }
    }
})

模块化

  1. 模块
// store/module/tabBarStore.js
import {observable,action} from 'mobx-miniprogram'
export default observable({
    count:1,
    setNum:action(function(num){
        this.count+=num
    })
})
  1. index
// store/index.js
import tabBarStore from './module/tabBarStore'
const store = Object.assign({}, tabBarStore)
export default store
  1. 使用方法与非模块化的方法一样

westore实现数据共享