微信小程序开发让前端飞微信小程序开发

小程序封装ajax等工具函数

2018-02-07  本文已影响211人  an祭

重复性代码

我们知道使用小程序自带的wx.request API可以发起网络请求,写法如下

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

但是做项目的时候碰到多个请求的时候,每次请求就需要写一遍,会存在很多重复代码,好在小程序项目目录里面有个util目录,里面也给我们写了个示例的formatTime工具函数,并将它exports出来了

// util.js
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

书写我们自己的工具函数

首先,我们将ajax函数封装下,返回一个promise, 将下面代码添加到 util目录下的util.js中

const ajax = (url, data, method, config = {}) => {
      let headerConfig = {  // 默认header ticket、token、params参数是每次请求需要携带的认证信息
        ticket: '...',
        token: '...',
        params: '...'
      }
      return new Promise((resolve, reject) => {  // 返回一个promise
        wx.request({
            url: host + url, // 拼接url
            data, 
            header: Object.assign({}, headerConfig, config), // 合并传递进来的配置
            method: method,
            success(data){
                resolve(data)
            }
        })
      })
}

我们再添加一个深拷贝的函数

function deepCopy(o, c) {
  var c = c || {}
  for (var i in o) {
    if (typeof o[i] === 'object') {
      //要考虑深复制问题了
      if (o[i].constructor === Array) {
        //这是数组
        c[i] = []
      } else {
        //这是对象
        c[i] = {}
      }
      deepCopy(o[i], c[i])
    } else {
      c[i] = o[i]
    }
  }
  return c
}

添加好后,再将函数exports出去 如下

module.exports = {
  formatTime: formatTime,
  ajax: ajax,
  deepCopy: deepCopy
}

使用工具函数Uti

首先我们在app.js顶部添加

const util = require('./utils/util.js')  // 将工具函数导入进来

然后在App函数中添加Util字段

Util:{
    ajax: util.ajax,
    deepCopy: util.deepCopy
}

页面中实例化getApp()函数后,我们就可以使用工具函数了

let app = getApp()

app.Util.ajax(....).then((data) => {  // 使用ajax函数
    // 请求相应后的操作
})  

tip

通过封装了工具类的代码提取出来封装成函数,我们就可以少写一些重复性的代码,并培养我们消除重复代码的习惯。

上一篇下一篇

猜你喜欢

热点阅读