微信小程序打夯之旅(四):Page能力增强

1,845

有一些常用的东西,如 http 请求、弹窗、错误处理等等,如果在每个页面都引用一遍,会增加不必的代码量,我们可以在 app.js 中对 Page 对象进行简单地封装,从而让 Page 的能力更强

Page封装

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()
  }
})