背景
主要是针对小程序开发中页面之间状态共享的问题,在涉及复杂的场景中比如用户身份状态、登录状态、支付情况等全局管理。
鉴于本人对Vue爱不释手,实现类似Vuex够用版。
遇到的问题
在使用百度小程序的 swan.navigateBack 进行回跳页面时,API中的方法参数不支持携带参数,只支持number参数。
所以就涉及了几个单独页面之间的通信问题。
解决方法
主要有以下4种方法,实现各page之间通信。
解决方法一:利用app.js globalData,设置公共变量
利用app.js的公共特性,将变量挂在APP上。1
2
3
4
5
6
7
8
9// app.js 启动文件
App({
    globalData: {
        isLogin: false,
        userInfo: null,
        networkError: false,
        networkType: 'none'
    }
})
在其他页面Page上使用时,使用:1
2
3// test.js
const app = getApp();
const commonParams = app.globalData.isLogin;
但是存在的缺点也十分明显,当数据量比较大、数据关系比较复杂时,维护会比较复杂,逻辑会很混乱。
解决方法二:利用storage
利用小程序的全局storage,对数据进行存取,原理类似于解决方案一。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23// 存储-异步
swan.setStorage({
    key: 'key',
    data: 'value'
});
// 存储-同步
swan.setStorageSync('key', 'value');
// 获取-异步
swan.getStorage({
    key: 'key',
    success: function (res) {
        console.log(res.data);
    },
    fail: function (err) {
        console.log('错误码:' + err.errCode);
        console.log('错误信息:' + err.errMsg);
    }
});
// 获取-同步
const result = swan.getStorageSync('key');
解决方法三: 利用事件总线EventBus
利用事件中心的进行订阅和发布。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56// event.js 事件中心
class Event {
    on(event, fn, ctx) {
        if (typeof fn !== 'function') {
            console.error('fn must be a function');
            return;
        }
        this._stores = this._stores || {};
        (this._stores[event] = this._stores[event] || []).push({
            cb: fn,
            ctx: ctx
        });
    }
    emit(event, ...args) {
        this._stores = this._stores || {};
        let store = this._stores[event];
        if (store) {
            store = store.slice(0);
            for (let i = 0, len = store.length; i < len; i++) {
                store[i].cb.apply(store[i].ctx, args);
            }
        }
    }
    off(event, fn) {
        this._stores = this._stores || {};
        // all
        if (!arguments.length) {
            this._stores = {};
            return;
        }
        // specific event
        let store = this._stores[event];
        if (!store) {
            return;
        }
        // remove all handlers
        if (arguments.length === 1) {
            delete this._stores[event];
            return;
        }
        // remove specific handler
        let cb;
        for (let i = 0, len = store.length; i < len; i++) {
            cb = store[i].cb;
            if (cb === fn) {
                store.splice(i, 1);
                break;
            }
        }
        return;
    }
}
module.exports = Event;
在app.js中进行声明和管理1
2
3
4
5
6// app.js
import Event from './utils/event';
App({
    event: new Event()
})
订阅的页面中,使用on方法进行订阅1
2
3
4
5
6
7
8
9
10
11
12// view.js 阅读页进行订阅
Page({
    // 页面在回退时,会调用onShow方法
    onShow() {
        // 支付成功的回调,调起下载弹层
        app.event.on('afterPaySuccess', this.afterPaySuccess, this);
    },
    afterPaySuccess(e) {
        // ....业务逻辑
    }
})
发布的页面中,根据业务情况进行发布emit1
2
3
4
5
6
7
8// paySuccess.js
const app = getApp();
app.event.emit('afterPaySuccess', {
    docId: this.data.tradeInfo.docId,
    triggerFrom: 'docCashierBack'
});
根据事件中心的发布和订阅,实现了页面之间的通信,就能实现比如页面在支付成功后回退时,页面状态的改变的场景,同时利于维护页面之间的数据关系,能通过在发布时传递参数,实现数据之间的通信。
解决方法四:easy-store
小程序目录:
| 1 | ├─images | 
easy-store
API
| 1 | app.store.install(this); // 注册使用 当前页面连接vuex | 
模板取值
| 1 | state和getter前用$ | 
实现方式
| 1 | /* | 
全局注册:
| 1 | import Store from './vuex/index'; | 
indnx页面注册使用
| 1 | const app = getApp() | 
| 1 | const app = getApp() | 
其他页面类似
| 1 | const app = getApp(); |