重复性代码
我们知道使用小程序自带的 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 tickettokenparams 参数是每次请求需要携带的认证信息
- 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
通过封装了工具类的代码提取出来封装成函数, 我们就可以少写一些重复性的代码, 并培养我们消除重复代码的习惯
来源: http://www.jianshu.com/p/9fec47e947dc