有一些經常使用的東西,如 http
請求、彈窗、錯誤處理等等,若是在每一個頁面都引用一遍,會增長沒必要的代碼量,咱們能夠在 app.js
中對 Page
對象進行簡單地封裝,從而讓 Page
的能力更強javascript
import $http from './plugins/http.js';
App({
// 展現成功彈窗(toast)
showSuccess (title, hideLoading) {
if (hideLoading) wx.hideLoading();
wx.showToast({ title, mask: true, duration: 500, icon: 'success' });
},
// 展現失敗彈窗(modal)
showError (title, content, hideLoading) {
if (hideLoading) wx.hideLoading();
wx.showModal({ title, content, showCancel: false });
},
// 加強Page能力,小程序不支持prototype的形式拓展能力
enhancePage() {
const oPage = Page;
Page = config => oPage(Object.assign(config, {
$http,
$showSuccess: this.showSuccess,
$showError: this.showError,
$showLoading: (title) => wx.showLoading({ mask: true, title: title }),
$hideLoading: () => wx.hideLoading(),
}));
},
onLaunch() {
this.enhancePage();
},
複製代碼
Page({
onLoad() {
this.$http('/api').then(() => ...)
this.$showSuccess('請求成功')
this.$showError('請求失敗', '請稍後重試')
this.$showLoading('數據加載中')
this.$hideLoading()
}
})
複製代碼