swanx

解释: 在小程序开发中,总会遇到多页面需要使用同一数据的情况,swanx是个轻量级数据管理工具,可以帮助开发者解决数据监听,多页面共用数据,子组件轻松获得父组件数据等功能。小程序中使用三方npm包方法,见npm使用说明。

方法参数

createStore方法参数说明:

创建store,可多页面共用一个,也可以每个页面独立使用自己的store。

返回值

返回storeManger对象,storeManger对象包括以下方法

storeManger对象的subscribe方法参数

storeManger对象的getState方法参数

storeManger对象的dispatch方法参数

storeBinding方法参数说明

在onLoad或者attached时,将创建的store和当前上下文绑定

返回值

connect方法参数说明

使用connect装饰过的组件或者页面,可以更方便的使用父级的store,避免逐层传递公用数据。

返回值

代码示例

在开发者工具中预览效果

扫码体验

请使用百度APP扫码

图片示例

安装

  1. npm install @smt-lib/swanx

代码示例1

  1. // store.js import {createStore} from '@smt-lib/swanx'; export const store = createStore({ state: { a: 0 }, fields: ['a'], actions: { changeA(num) { return { ...this.state, a: this.state.a + num }; } } }); // a页面 import { store } from "./store"; import { storeBinding } from "@smt-lib/swanx"; Page({ data: { a: 0 }, storeBind() { this.unbindStore = storeBinding(this, store); swan.showToast({ title: '已绑定', icon: 'none' }); }, myChangeA() { store.dispatch('changeA', 1); swan.showModal({ title: 'swanx', content: 'data.a=' + this.data.a, confirmText: '确定', showCancel: false }); }, destory() { if (this.unbindStore) { this.unbindStore(); swan.showToast({ title: '已取消绑定', icon: 'none' }); } else { swan.showModal({ title: 'swanx', content: '请先绑定store', confirmText: '确定', showCancel: false }); } }, unOnload() { this.unbindStore && this.unbindStore(); } });

代码示例2

  1. // store.js import { createStore } from "@smt-lib/swanx"; export const store = createStore({ state: { a: 1, b: { d: 4, e: 5 }, c: 3 }, fields: ['a', 'b.d'], actions: { changeA(num) { return { ...this.state, a: this.state.a + num }; }, addD() { return { ...this.state, b: { ...this.state.b, d: this.state.b.d + 1 } }; } } }); // a页面 import { store } from "./store"; import { storeBinding } from "@smt-lib/swanx"; Page({ data: {}, onLoad() { this.unbindStore = storeBinding(this, store); console.log(this.store); }, myChangeA() { store.dispatch('changeA', 1); }, unOnload() { this.unbindStore(); } }); // a页面的b组件 import { connect } from "@smt-lib/swanx"; const newComponent = connect(Component); newComponent({ properties: {}, pageLifetimes: { attached() { console.log(this.data.a); store.subscribe(['b.d'], state => { console.log(state.b); }); } }, method: { myChangeA() { this.store.dispatch('changeA', 1); } } });