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

有一些经常使用的东西,如 http 请求、弹窗、错误处理等等,若是在每一个页面都引用一遍,会增长没必要的代码量,咱们能够在 app.js 中对 Page 对象进行简单地封装,从而让 Page 的能力更强javascript

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()
  }
})
复制代码
相关文章
相关标签/搜索