wx: 小程序公共机制

注册机制:

//app.js
let Api = require('./http/api.js')
let request = require('./http/request.js')
let config = require('./env/index.js')
let env = 'dev'
App.version = '1.0.0'
App.config = config[env] || {}
App.config.env = env
App.config.mockApi = config.mockApi
//App实例只供页面使用
App({
  // 全局注册APi
  Api,
  config: config[env],
  get: request.fetch,
  post: (url, data, option) => {
    option.method = 'POST'
    return request.fetch(url, data, option)
  },
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

存储机制:

/** 按模块集中管理storage **/
const STORAGE_KEY = 'sym_pay';
module.exports = {
  setItem(key, value, module_name) {
    // 如果有分模块的化就模块进行存储,没有的话直接全局存储
    if (module_name) {
      let module_name_info = this.getItem(module_name)
      module_name_info[key] = value;
      wx.setStorageSync(module_name, module_name_info)
    } else {
      wx.setStorageSync(key, value)
    }
  },
  // 获取值
  getItem(key, module_name) {
    if (module_name) {
      let value = this.getItem(module_name)
      if (value) return value[key]
      return '';
    } else {
      return wx.getStorageSync(key)
    }
  },
  clear(key) {
    // 如果没有传key的话全部删除
    key ? wx.removeStorageSync(key) : wx.clearStorageSync()
  }
}

路由机制:

/**
 * @author Nyan Shen
 * @description 通用的路由跳转机制
 */

const routerPath = {
  'index': '/pages/index/index',
  'log': '/pages/logs/logs',
  'pay': '/pages/pay/index',
  'activity': '/pages/activity/index'
}
module.exports = {
  push(path, option = {}) {
    if (typeof path === 'string') {
      option.path = path;
    } else {
      option = path;
    }
    let url = routerPath[option.path]
    // query跳转参数,openType跳转方式,duration时间延迟
    let { query = {}, openType, duration } = option
    let urlParam = this.parseDataObjectToUrlParam(query);
    if (urlParam) {
      url += '?' + urlParam;
    }
    duration ? setTimeout(() => {
      this.to(openType, url)
    }, duration) : this.to(openType, url)
  },
  to(openType, url) {
    let obj = { url }
    if (openType === 'redirect') {
      wx.redirectTo(obj)
    } else if (openType === 'reLaunch') {
      wx.reLaunch(obj)
    } else if (openType === 'back') {
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.navigateTo(obj)
    }
  },
  parseDataObjectToUrlParam(dataObject) {
    let arr = [];
    for (let key in dataObject) {
      arr.push(key + '=' + dataObject[key])
    }
    return arr.join('&')
  }
}

 请求机制:

/**
 * @author Nyan Shehn
 * @description 通用请求封装 
 * */
let store = require('../utils/store.js')
const system = store.getSystemInfo()
const clientInfo = {
  'clientType': 'mp', //小程序
  'appName': 'sym_wx_small_progress',
  'model': system.model,
  'os': system.system,
  'screen': system.screenWidth + '*' + system.screenHeight,
  'version': App.version,
  'channel': 'miniprogram'
}
const errMsg = '服务异常,请稍后再试'
module.exports = {
  fetch(url, data = {}, { method = 'GET', loading = true, toast = true, isMock = false }) {
    return new Promise((resolve, reject) => {
      if (loading) {
        wx.showLoading({
          title: '加载中......',
          mask: true
        })
      }
      let baseUrl = isMock ? App.config.mockApi : App.config.baseApi
      wx.request({
        url: baseUrl + url,
        data,
        method,
        header: {
          'clientInfo': JSON.stringify(clientInfo)
        },
        success: function (result) {
          let res = result.data
          if (res.code === 0) {
            if (loading) {
              wx.hideLoading()
            }
            resolve(res.data)
          } else {
            if (toast) {
              wx.showToast({
                mask: true,
                title: res.message,
                icon: 'none'
              })
            } else {
              wx.hideLoading()
            }
            reject(res)
          }
        },
        fail: function (e = { code: -1, msg: errMsg, errMsg }) {
          let msg = e.errMsg
          if (msg == 'request:fail timeout') {
            msg = '服务器请求超时,请稍后再试'
          }
          wx.showToast({
            title: msg,
            icon: 'none'
          })
          reject(e)
        }
      })
    })
  }
}
原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/13067708.html