微信小程序-page

封装Page

封装思路:实现所有页面所有事件统一处理。如果单独页面直接定义页面事件,公共方法被重写。

第一步:注入APP方法

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
// 小程序全局对象
const WeChat = {};

// 微信注入的App方法
WeChat.App = App;
// 微信注入的getApp方法
WeChat.getApp = getApp;
// 微信注入的Page方法
WeChat.Page = Page;
// 微信注入的Component方法
WeChat.Component = Component;
// 微信注入的API
WeChat.wx = {};
Object.assign(WeChat.wx, wx);

/**
* 注册页面
*/
WeChat.register = function (PageClass) {
let page = Utils.newInstance(PageClass);
// 此处可以统一处理公共方法
WeChat.Page(page);
};

/**
* 初始化组件
*/
WeChat.initComponent = function (ComponentClass) {
let component = Utils.newInstance(ComponentClass);
WeChat.Component(component);
};

export default WeChat;

此处newInstance()方法实现 通过Class类型创建一个对象(把所有继承来的属性方法设置到这个对象的普通属性中)


第二步:建公共BasePage方法

1
2
3
4
5
6
7
8
9
10
11
12
export default class BasePage {
constructor() { }
// 生命周期函数--监听页面加载
onLoad(o) { }
onReady(o) { }
onShow(o) { }

// 自定义全局方法 提示等
showErrorMsg(title) {
wx.showModal({})
}
}


第三步: 页面实例化BasePage

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
import {WeChat, BasePage,} from '../../lib';

class Home extends BasePage {
constructor() {
super();
this.setDefaultData({
// 默认数据
data: null,

});
}
static onShareAppMessage() {
return {
title: `分享标题`,
path: `/pages/index`
};
}

events = {
// 绑定事件
bindClick() {
this.setData({data: 1});
}
};
onPageLoad() { }
}

WeChat.register(Home);

结语:每个页面JS都继承BasePage的公共方法,通过register重新绑定到Page方法上面。以此来统一处理所以页面事件。

下期更新Component组件封装

亲,赏一个呗,一分也是爱!
0%